写一个简单日志器

时间:2022-12-12 22:00:38
import logging

my_logger = logging.getLogger()#默认不传参数为root

#将日志写入到文件中去
fn = logging.FileHandler("my.log")

#设置等级
fn.setLevel(logging.INFO)

#格式化输出:异常产生时间、级别、异常消息等
formatter =  logging.Formatter(
    "时间:%(asctime)s"
    "日志级别:%(levelname)s"
    "日志消息:%(message)s"
    "日志名称:%(name)s"
)
fn.setFormatter(formatter)

#生效
my_logger.addHandler(fn)


if __name__ == '__main__':
    try:
        a = 1/0
    except Exception as e:
        my_logger.error(e)

    with open("my.log","r") as f:
        print(f.read())

控制台结果:

时间:2019-05-03 19:37:56,145日志级别:ERROR日志消息:division by zero日志名称:root