【python日志】python的日志模块和记录日志

python日志模块

 

一、logging模块

Python中有一个模块logging,可以直接记录日志

#   日志级别
# CRITICAL 50
# ERROR    40
# WARNING  30
# INFO     20
# DEBUG    10 

logging.basicConfig()函数中的具体参数:
filename:   指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中;
filemode:   文件打开方式,在指定了filename时使用这个参数,默认值为“w”还可指定为“a”;
format:      指定handler使用的日志显示格式;
datefmt:    指定日期时间格式。,格式参考strftime时间格式化(下文)
level:        设置rootlogger的日志级别
stream:     用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。
                  若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数中可能用到的格式化信息:

%(name)s

Logger的名字

%(levelno)s

数字形式的日志级别

%(levelname)s

文本形式的日志级别

%(pathname)s

调用日志输出函数的模块的完整路径名,可能没有

%(filename)s

调用日志输出函数的模块的文件名

%(module)s

调用日志输出函数的模块名

%(funcName)s

调用日志输出函数的函数名

%(lineno)d

调用日志输出函数的语句所在的代码行

%(created)f

当前时间,用UNIX标准的表示时间的浮 点数表示

%(relativeCreated)d

输出日志信息时的,自Logger创建以 来的毫秒数

%(asctime)s

字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒

%(thread)d

线程ID。可能没有

%(threadName)s

线程名。可能没有

%(process)d

进程ID。可能没有

%(message)s

用户输出的消息

二、logging模块测试

1、打印日志到标准输出中

import logging
import os 

logging.basicConfig(filename=os.path.join(os.getcwd(),'log.txt'),level=logging.DEBUG)
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message') 

输出结果

C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe D:/pyworkpeace/tupian.py 'https://www.tianyancha.com/login'
WARNING:root:warning message

Process finished with exit code 0 

可以看出默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志。默认的日志的格式为:

日志级别:Logger名称:用户输出消息

2、将日志文件输入到文件中

import os
logging.basicConfig(filename=os.path.join(os.getcwd(),'log.txt'),level=logging.DEBUG)
logging.debug('this is a message') 

运行这三行代码后会在安装Python的目录中出现一个log.txt文件,文件内容

DEBUG:root:this is a message
DEBUG:root:debug message 

3、自定义格式,输出日志文件

复制代码
# -*-coding:utf-8-*-

import logging


def console_out(logFilename):
    ''''' Output log to file and console '''
    # Define a Handler and set a format which output to file
    logging.basicConfig(
        level=logging.DEBUG,  # 定义输出到文件的log级别,大于此级别的都被输出
        format='%(asctime)s  %(filename)s : %(levelname)s  %(message)s',  # 定义输出log的格式
        datefmt='%Y-%m-%d %A %H:%M:%S',  # 时间
        filename=logFilename,  # log文件名
        filemode='w')  # 写入模式“w”或“a”
    # Define a Handler and set a format which output to console
    console = logging.StreamHandler()  # 定义console handler
    console.setLevel(logging.INFO)  # 定义该handler级别
    formatter = logging.Formatter('%(asctime)s  %(filename)s : %(levelname)s  %(message)s')  # 定义该handler格式
    console.setFormatter(formatter)
    # Create an instance
    logging.getLogger().addHandler(console)  # 实例化添加handler

    # Print information              # 输出日志级别
    logging.debug('logger debug message')
    logging.info('logger info message')
    logging.warning('logger warning message')
    logging.error('logger error message')
    logging.critical('logger critical message')


if __name__ == "__main__":
    console_out('logging.log') 

复制代码

输出结果:

此时也会自动生成一个日志文件,日志文件和运行文件在同一个文件夹中,文件名logging.log

2017-10-23 Monday 11:37:59 hgghf : DEBUG logger debug message
2017-10-23 Monday 11:37:59 hgghf : INFO logger info message
2017-10-23 Monday 11:37:59 hgghf : WARNING logger warning message
2017-10-23 Monday 11:37:59 hgghf : ERROR logger error message
2017-10-23 Monday 11:37:59 hgghf : CRITICAL logger critical message

修改输出路径:

filename='/tmp/test1.log',  # log文件名
当将脚本中这行代码换一下,那么我们输出日志的路径地址就换成了D:\tmp
下面的方式同样可以达到上述结果 

 4、自定义输出位置

复制代码
import logging  
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  
                    datefmt='%a, %d %b %Y %H:%M:%S',  
                    filename='/tmp/test.log',  
                    filemode='w')  
  
logging.debug('debug message')  
logging.info('info message')  
logging.warning('warning message')  
logging.error('error message')  
logging.critical('critical message')  

复制代码

由于运行脚本放在D:\pyworkpeace\下,输出文件在D盘tmp文件夹下test.log,内容如下:

Mon, 23 Oct 2017 15:00:05 tupian.py[line:11] DEBUG debug message
Mon, 23 Oct 2017 15:00:05 tupian.py[line:12] INFO info message
Mon, 23 Oct 2017 15:00:05 tupian.py[line:13] WARNING warning message
Mon, 23 Oct 2017 15:00:05 tupian.py[line:14] ERROR error message
Mon, 23 Oct 2017 15:00:05 tupian.py[line:15] CRITICAL critical message

三、Logger,Handler,Formatter,Filter的概念

原文:https://www.cnblogs.com/bethansy/p/7716747.html

如何优雅的记录日志

工作3年,解决线上问题无数。日志对于定位和分析问题的重要行不言而喻。那么python怎么优雅的记录日志呢

    首先,python记录日志,首选是logging模块,没有啥争议。

    日志的一般写法是这样的:

logging.info('info message')

logging.error('error message')

   这种日志一般作用不大,只能定位到程序正常执行时执行到哪一步和打印输出一些信息。对于一些异常之列的信息,我们需要使用try:execpt获取。

    很多人是这样记录异常日志的:

>>> def test(a):

...     int(a)

>>> try:

...     test("a")

... except Exception as e:

...     print(e.message)

...

invalid literal for int() with base 10: 'a'

    开发人员只看到一行python的报错,是很难定位问题的。我们需要错误的堆栈信息,定位到错误的源头,例如:

>>> try:

...     test("a")

... except Exception as e:

...     logging.exception(e)

...

ERROR:root:invalid literal for int() with base 10: 'a'

Traceback (most recent call last):

  File "<stdin>", line 2, in <module>

  File "<stdin>", line 2, in test

ValueError: invalid literal for int() with base 10: 'a'

使用logging.exception 的话就可以拿到堆栈信息。是不是很神奇,我们一起来看看logging的源码,看它为啥能拿到堆栈信息。

对比error

发现,exception其实是调用error的,唯一的不同时,有一个默认参数exc_info=True。。。一直查看它的调用关系,到了这里:

看到这里,应该都清楚了,其实他使用的是sys.exc_info(),这个python内置sys函数。。。

明白了logging.exception的原理后,我们就可以这样定义日志了:

>>> try:

...     test("a")

... except Exception as e:

...     logging.error("执行test函数报错", exc_info=True)

...

ERROR:root:执行test函数报错

Traceback (most recent call last):

  File "<stdin>", line 2, in <module>

  File "<stdin>", line 2, in test

ValueError: invalid literal for int() with base 10: 'a'

这样,不仅可以自定义logging,还可以打印堆栈信息。info同理,只要把error改成info即可


原文:https://blog.csdn.net/u011510825/article/details/83929151 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值