Home > Backend Development > Python Tutorial > How to configure Python logs

How to configure Python logs

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-05-24 15:37:15
forward
1761 people have browsed it

Configuration

Configuration tendency

  • Only output to file

  • Rotate by time, default is 7d

  • Log format: only record necessary information

import logging
from logging.handlers 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: 文件名
    :param default_dir: 
    :param logformat: 
    :param loglevel: 
    :param backup_count: 
    :param encoding: 
    :param delay: 
    :return: 
    """
    levelint = {
        "debug": logging.DEBUG,
        "info": logging.INFO,
        "warn": logging.WARN,
        "error": logging.ERROR
    }[loglevel]
    if not filename.startswith("/"):
        filename = path.join(default_dir, filename)
    logging.basicConfig(
        format=logformat,
        level=levelint,
        handlers=[
            TimedRotatingFileHandler(
                filename,
                when="d",
                backupCount=backup_count,
                encoding=encoding,
                delay=delay,
            )
        ]
    )
Copy after login

Usage

  • At the very beginning of the program Start initialization (I usually put it on the first line)

init_log_config("log1.log", loglevel="debug")
import os, sys
Copy after login
  • Used in business

logging.info("Start Do something")
Copy after login

The above is the detailed content of How to configure Python logs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template