首页 > 代码库 > python中的日志模块logging

python中的日志模块logging

1、日志级别5个:

警告Warning 一般信息Info  调试 Debug  错误Error 致命Critical

2、禁用日志方法

logging.disable(logging.DEBUG)

3、将日志写入文件

logging.basicConfig(filename=‘log.txt‘, level=logging.CRITICAL,
                    format=‘ %(asctime)s - %(levelname)s - %(message)s‘)

4、格式化输出日志信息

注意事项:

  1、日志输出的文件时,涉及写入日志文件的日志配置应该放到日志配置的首行,否则会受到前面日志配置的干扰。

#!/usr/bin/env python
# coding=utf-8

import logging
import os

logging.basicConfig(filename=‘log.txt‘, level=logging.CRITICAL,
                    format=‘ %(asctime)s - %(levelname)s - %(message)s‘)
logging.basicConfig(level=logging.DEBUG, format=‘ %(asctime)s - %(levelname)s - %(message)s‘)

#  禁用日志模块的调试信息
#  logging.disable(logging.DEBUG)

logging.debug(‘Start of program‘)

#  判断日志文件是否存在
if os.path.exists(‘log.txt‘):
    print "Have found the log.txt"
    logging.critical("good")
else:
    logging.critical("/home/log.txt is not existed!!!")

def factorial(n):
    logging.debug(‘Start of factorial(%s%%)‘ % (n))
    total = 1
    for i in range(1, n + 1):
        total *= i
        logging.debug(‘i is ‘ + str(i) + ‘, total is ‘ + str(total))
    logging.debug(‘End of factorial(%s%%)‘ % (n))
    return total

print(factorial(5))
logging.debug(‘End of program‘)

 

python中的日志模块logging