python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python日志配置

Python日志极简配置示例

作者:浮生若梦的编程

这篇文章主要为大家介绍了Python日志极简配置示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

配置

配置倾向

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,
            )
        ]
    )

使用方式

init_log_config("log1.log", loglevel="debug")
import os, sys
logging.info("Start Do something")

以上就是Python日志极简配置的详细内容,更多关于Python日志配置的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文