Logging模块
跳转到导航
跳转到搜索
This module defines functions and classes which implement a flexible event logging system for applications and libraries.
logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略
#!/usr/bin/python
#-*- coding:utf-8 -*-
import logging
import os
import urllib
import time
def logs(message):
logspath = '/data/logs/php/'
if os.path.exists(logspath) is False:
os.makedirs(logspath)
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=logspath+'checkphp-fpm.log',
filemode='a')
return logging.info(message)
if __name__ == '__main__':
message="try 3 time"
logs(message)
'''
cat php/checkphp-fpm.log
Thu, 12 Jan 2017 15:58:00 py.py[line:14] INFO try 3 time
'''
see also
https://docs.python.org/2/library/logging.html
http://www.cnblogs.com/captain_jack/archive/2011/01/21/1941453.html
http://www.pythonclub.org/modules/logging http://www.pythonclub.org/modules/logging http://www.cnblogs.com/captain_jack/archive/2011/01/21/1941453.html
http://pythonguidecn.readthedocs.io/zh/latest/writing/logging.html