SoFunction
Updated on 2024-11-13

Python Logging Minimalist Configuration Example

configure

Configuration preferences

  • Output to file only
  • Rotation by time, default 7d
  • Log format: record only the necessary information
import logging
from  import TimedRotatingFileHandler
from os import path
def init_log_config(
        filename: str,
        *,
        default_dir="/var/log",
        logformat: str = ("[%(levelname)s %(asctime)s %(process)d_%(threadName)s %(filename)s:%(lineno)s:%(funcName)s] "
                          "%(message)s"),
        loglevel: str = "warn",
        backup_count: int = 7,
        encoding="utf-8",
        delay=True,
):
    """
    :param filename: filename
    :param default_dir.
    :param logformat.
    :param loglevel: :param backup_count: :param
    :param backup_count: :param encoding: :param encoding
    :param encoding: :param delay: :param encoding: :param encoding
    :param delay: :return: :return
    :return.
    """
    levelint = {
        "debug": ,
        "info": ,
        "warn": ,
        "error": 
    }[loglevel]
    if not ("/"):
        filename = (default_dir, filename)
    (
        format=logformat,
        level=levelint,
        handlers=[
            TimedRotatingFileHandler(
                filename,
                when="d",
                backupCount=backup_count,
                encoding=encoding,
                delay=delay,
            )
        ]
    )

Usage

  • Start initialization at the very, very beginning of the program (I usually put it on the first line)
init_log_config("", loglevel="debug")
import os, sys
  • Used in business
("Start Do something")

Above is the details of Python logging minimalist configuration, more information about Python logging configuration please pay attention to my other related articles!