python使用logging模块实现日志写入
其一
"""
logging配置
"""
import os
import logging.config
import time
# 定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]' # 其中name为getlogger指定的名字
console_format = '[%(asctime)s][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]' # 其中name为getlogger指定的名字
# simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
simple_format = '%(message)s'
sender_format = 'from sender : %(message)s'
# 定义日志输出格式 结束
# print(os.path.dirname(os.path.abspath(__file__)))
logfile_dir = os.path.dirname(os.path.abspath(__file__)) + "/" + "log" # log文件的目录
if not os.path.exists(logfile_dir):
os.makedirs(logfile_dir)
# if not os.path.exists(logfile_send_dir):
# os.makedirs(logfile_send_dir)
current_day = time.strftime("%Y-%m-%d", time.localtime())
log_file_name = logfile_dir +'/'+ current_day +'.log'
app_file_name = logfile_dir + '/app.log'
send_file_name = logfile_dir + '/send.log'
# log文件的全路径
log_file_path = os.path.join(logfile_dir, log_file_name)
# print(logfile_path)
app_file_path = os.path.join(logfile_dir, app_file_name)
send_file_path = os.path.join(logfile_dir, send_file_name)
# print(logfile_send_path)
# log配置字典
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
'sender':{
'format': sender_format
}
},
'filters': {},
'handlers': {
# 打印到终端的日志
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler', # 打印到屏幕
'formatter': 'standard'
},
# 打印到文件的日志,收集info及以上的日志
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'standard',
'filename': log_file_path, # 日志文件
'maxBytes': 1024*1024*50, # 日志大小 5M
'backupCount': 20,
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
},
'timedRotating': {
'level': 'INFO',
'class': 'logging.handlers.TimedRotatingFileHandler',
'when': 'midnight',
'interval': 1,
'filename': app_file_path,
'encoding': 'utf-8',
'backupCount': 5,
'formatter': 'simple'
},
'sendRotating': {
'level': 'INFO',
'class': 'logging.handlers.TimedRotatingFileHandler',
'when': 'midnight',
'interval': 1,
'filename': send_file_path,
'encoding': 'utf-8',
'backupCount': 5,
'formatter': 'sender'
}
},
'loggers': {
# logging.getLogger(__name__)拿到的logger配置
'dev': {
'handlers': ['timedRotating','default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'level': 'INFO',
'propagate': True, # 向上(更高level的logger)传递
},
'prod': {
'handlers': ['sendRotating','default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'level': 'INFO',
'propagate': True, # 向上(更高level的logger)传递
},
},
}
logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置
logger = logging.getLogger('dev') # 生成一个log实例
send_logger = logging.getLogger('prod') # 生成一个log实例
if __name__ == '__main__':
for i in range(10):
logger.info('It works! {}'.format(i)) # 记录该文件的运行状态
send_logger.info('hhhhh --> {}'.format(i))
注意事项:
eg:
"""
logging配置
"""
import os
import logging.config
import time
# 定义三种日志输出格式 开始
standard_format = "[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]" \
"[%(levelname)s][%(message)s]" # 其中name为getlogger指定的名字
simple_format = "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s"
id_simple_format = "[%(levelname)s][%(asctime)s] %(message)s"
# 定义日志输出格式 结束
logfile_dir = os.path.dirname(os.path.abspath(__file__)) + "/" + "log" # log文件的目录
current_data = time.strftime("%Y-%m-%d", time.localtime())
# logfile_name = "data/yolo_app.log" # log文件名
logfile_name = logfile_dir + "/" + current_data + ".log"
have_result_file = logfile_dir + "/" + current_data + "_haveResults.log"
no_result_file = logfile_dir + "/" + current_data + "_noResults.log"
exclusive_file = logfile_dir + "/" + current_data + "_exclusive.log"
send_file = logfile_dir + "/" + current_data + "_send.log"
# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
os.mkdir(logfile_dir)
# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)
# log配置字典
LOGGING_DIC = {
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"standard": {
"format": standard_format
},
"simple": {
"format": simple_format
},
},
"filters": {},
"handlers": {
# 打印到终端的日志
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler", # 打印到屏幕
"formatter": "simple"
},
# 打印到文件的日志,收集info及以上的日志
"default": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler", # 保存到文件
"formatter": "standard",
"filename": logfile_path, # 日志文件
"maxBytes": 1024*1024*5, # 日志大小 5M
"backupCount": 5,
"encoding": "utf-8", # 日志文件的编码,再也不用担心中文log乱码了
},
"have": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler", # 保存到文件
"formatter": "simple",
"filename": have_result_file, # 日志文件
"maxBytes": 1024*1024*5, # 日志大小 5M
"backupCount": 5,
"encoding": "utf-8", # 日志文件的编码,再也不用担心中文log乱码了
},
"no": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler", # 保存到文件
"formatter": "simple",
"filename": no_result_file, # 日志文件
"maxBytes": 1024 * 1024 * 5, # 日志大小 5M
"backupCount": 5,
"encoding": "utf-8", # 日志文件的编码,再也不用担心中文log乱码了
},
"exc": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler", # 保存到文件
"formatter": "simple",
"filename": exclusive_file, # 日志文件
"maxBytes": 1024 * 1024 * 5, # 日志大小 5M
"backupCount": 5,
"encoding": "utf-8", # 日志文件的编码,再也不用担心中文log乱码了
},
"s": {
"level": "DEBUG",
"class": "logging.handlers.RotatingFileHandler", # 保存到文件
"formatter": "simple",
"filename": send_file, # 日志文件
"maxBytes": 1024 * 1024 * 5, # 日志大小 5M
"backupCount": 5,
"encoding": "utf-8", # 日志文件的编码,再也不用担心中文log乱码了
},
},
"loggers": {
# logging.getLogger(__name__)拿到的logger配置
"dev": {
# "handlers": ["default", "console"], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
"handlers": ["default"],
"level": "DEBUG",
"propagate": True, # 向上(更高level的logger)传递
},
"haveResult": {
# "handlers": ["default", "console"], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
"handlers": ["have"],
"level": "DEBUG",
"propagate": True, # 向上(更高level的logger)传递
},
"noResult": {
# "handlers": ["default", "console"], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
"handlers": ["no"],
"level": "DEBUG",
"propagate": True, # 向上(更高level的logger)传递
},
"exclusive": {
# "handlers": ["default", "console"], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
"handlers": ["exc"],
"level": "DEBUG",
"propagate": True, # 向上(更高level的logger)传递
},
"send": {
# "handlers": ["default", "console"], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
"handlers": ["s"],
"level": "DEBUG",
"propagate": True, # 向上(更高level的logger)传递
},
},
}
logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置
# logger = logging.getLogger(__name__) # 生成一个log实例
logger = logging.getLogger("dev") # 生成一个log实例
haveRes_logger = logging.getLogger("haveResult") # 生成一个log实例
noRes_logger = logging.getLogger("noResult") # 生成一个log实例
exclusive_logger = logging.getLogger("exclusiveResult") # 生成一个log实例
send_logger = logging.getLogger("sendResult") # 生成一个log实例
# logger.setLevel(logging.DEBUG)
# print(logger)
# logger.info("It works!") # 记录该文件的运行状态
其二:
# -*- coding: utf-8 -*-
import time
import logging
import os
from logging.handlers import RotatingFileHandler
project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(project_dir)
log_path = project_dir + "/log"
print(log_path)
class Log(logging.Logger):
def __init__(self, logname):
# super(MyLogger, self).__init__(filename)
filename = log_path + logname + '.log'
logging.Logger.__init__(self, filename)
# 设置日志格式
fmtHandler = logging.Formatter('%(asctime)s [%(filename)s:%(lineno)s][%(levelname)s] %(message)s')
# 终端log输出流设置
try:
consoleHd = logging.StreamHandler()
consoleHd.setLevel(logging.ERROR)
consoleHd.setFormatter(fmtHandler)
self.addHandler(consoleHd)
except Exception as reason:
self.error("%s" % reason)
# 设置log文件
try:
os.makedirs(os.path.dirname(filename))
except Exception as reason:
pass
try:
# 设置回滚日志,每个日志最大10M,最多备份5个日志
fileHd = logging.handlers.RotatingFileHandler(
filename, maxBytes=10 * 1024 * 1024, backupCount=5)
# fileHd = logging.FileHandler(filename)
fileHd.setLevel(logging.INFO)
fileHd.setFormatter(fmtHandler)
self.addHandler(fileHd)
except Exception as reason:
self.error("%s" % reason)
return
if __name__ == '__main__':
test1 = Log('test1')
test2 = Log('test2')
# while True:
test1.info("test1")
test2.error("test2")