commercialcompany/logger.py

23 lines
843 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import logging
from logging.handlers import RotatingFileHandler
# 创建一个logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.INFO) # 可以根据需要设置为DEBUG, ERROR, WARNING等
# 创建一个handler用于写入日志文件
file_handler = RotatingFileHandler('app.log', maxBytes=1024*1024*5, backupCount=5)
file_handler.setLevel(logging.INFO)
# 创建一个handler用于将日志输出到控制台
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.ERROR) # 只输出error级别的到控制台
# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
# 给logger添加handler
logger.addHandler(file_handler)
logger.addHandler(stream_handler)