码迷,mamicode.com
首页 > 其他好文 > 详细

logging日志模块

时间:2019-08-23 22:49:38      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:txt   函数   mode   logging   try   for   ogg   必须   文件的   

1.捕获异常并写入日志

import logging

obj = logging.basicConfig(   # 这里用basicConfig是配置,如果要打印到多个文件中是不行的,必须自定义
    filename=1x.txt,        # 要写入的文件名,这里如果没设置写入模式会默认追加a模式,要设置模式可以用filemode=
    format = %(asctime)s - %(name)s - %(levelname)s - %(module)s:  %(message)s %(pathname)s ,
      datefmt=%Y-%m-%d %H:%M:%S,   # 时间格式化
    level=logging.DEBUG,  # 设置写入的日志级别,不设置会默认到warning
                            # 日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG

)

import traceback
def func():
    try:
        a=a+1

    except Exception as e:
        # 获取当前错误的堆栈信息
        mg = traceback.format_exc()
        logging.error(mg)
func()

2.这里format中的一些格式化:

asctime 时间,有默认的格式

name 操作的用户名

levename 日志的级名

module 所在模块名

message 日志等级的标志

level 定义级数

pathname 打印当前执行程序的路径

lineno 打印日志的当前函数

 

3.日志写入多个文件的时候

import logging

file_handle = logging.FileHandler(1x.txt,encoding=UTF-8)  # 设置写入的文件名

log_fmt = logging.Formatter(fmt=%(asctime)s %(name)s %(levelname)s %(module)s : %(message)s )  # 设置写入格式
file_handle.setFormatter(log_fmt)

loggin1 = logging.Logger(name=x1,level=logging.ERROR)
loggin1.addHandler(file_handle)

loggin1.error(12314)


file_handle2 = logging.FileHandler(2x.txt,encoding=UTF-8)  # 设置写入的文件名

log_fmt2 = logging.Formatter(fmt=%(asctime)s %(name)s %(levelname)s %(module)s : %(message)s )  # 设置写入格式
file_handle2.setFormatter(log_fmt)

loggin2 = logging.Logger(name=x1,level=logging.ERROR)
loggin2.addHandler(file_handle)

loggin2.error(12314)

 

logging日志模块

标签:txt   函数   mode   logging   try   for   ogg   必须   文件的   

原文地址:https://www.cnblogs.com/whileke/p/11402837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!