首页 > 代码库 > 创建自定义带时间戳的日志信息

创建自定义带时间戳的日志信息

1.datetime中的datetime.datetime.now()生成的时间中自带有毫秒值
# coding=utf-8
import time,datetime
def log(level,con):
try:
with open(‘E:/test.log‘,‘a‘) as f:
# t = time.strftime("%Y-%M-%d %H:%m:%S")
now = datetime.datetime.now()
con = str(now) +" "+level+":"+con+"\n"
f.write(con)
except Exception,e:
print e


log("INFO","start test")
2.使用logging模块自带的配置

    # coding = utf-8

    import logging 

   def f(filename):

                   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=filename, \

                    filemode=‘w‘) 

                   return logging

f(filename).debug(‘debug message‘) 

f(filename).info(‘info message‘) 

f(filename).warning(‘warning message‘) 

f(filename).error(‘error message‘) 

f(filename).critical(‘critical message‘)

创建自定义带时间戳的日志信息