日志输出流较佳实践[较佳实践]

总体实践

#!/bin/python3
# coding: utf-8

import sys
import logging

file_handler = logging.FileHandler(filename="./xxx.log")
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [file_handler, stdout_handler]


logging.basicConfig(
    level=logging.INFO,
    # 取消filename注释则会打印日志到log文件, filename 优先级大于stream
    # filename="./xxx.log", filemode="w+",
    # stream=sys.stdout,
    handlers=handlers,
    format=("%(asctime)s.%(msecs)03d %(process)d:%(thread)d "
            "%(levelname)s %(name)s:%(lineno)d %(message)s"))
LOG = logging.getLogger(__name__)

详细解释

使日志输出到日志文件,print输出到控制台

logging.basicConfig(
    level=logging.INFO,
    filename="./xxx.log", filemode="w+",
    format=("%(asctime)s.%(msecs)03d %(process)d:%(thread)d "
            "%(levelname)s %(name)s:%(lineno)d %(message)s"))
LOG = logging.getLogger(__name__)

使日志输出到控制台

logging.basicConfig(
    level=logging.INFO,
    # 取消filename注释则会打印日志到log文件, filename 优先级大于stream
    # filename="./xxx.log", filemode="w+",
    stream=sys.stdout,
    format=("%(asctime)s.%(msecs)03d %(process)d:%(thread)d "
            "%(levelname)s %(name)s:%(lineno)d %(message)s"))
LOG = logging.getLogger(__name__)

控制日志输出到多个流

file_handler = logging.FileHandler(filename="./xxx.log")
stdout_handler = logging.StreamHandler(sys.stdout)
# 这里可以控制是多个流还是单个流
handlers = [file_handler, stdout_handler]

logging.basicConfig(
    level=logging.INFO,
    handlers=handlers,
    format=("%(asctime)s.%(msecs)03d %(process)d:%(thread)d "
            "%(levelname)s %(name)s:%(lineno)d %(message)s"))
LOG = logging.getLogger(__name__)
上一篇:Go语言net/http包使用详细介绍


下一篇:职责链模式 -- C++