python logger
Posted keep-minding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python logger相关的知识,希望对你有一定的参考价值。
import os
import logging
from logging.handlers import TimedRotatingFileHandler
from logging import handlers
import socket
def logger(path, loggername=None):
os.makedirs(path, exist_ok=True)
if loggername is None:
loggername = ‘‘
logger = logging.getLogger(loggername)
logger.setLevel(logging.INFO)
handler = TimedRotatingFileHandler(path,
when="midnight", # midnight
interval=1,
backupCount=30)
logFormatter = logging.Formatter(‘%(asctime)s %(name)-12s %(levelname)-8s %(message)s‘)
handler.setFormatter(logFormatter)
logger.addHandler(handler)
return logger
def critical_email_logger():
HOST = ‘Host.com‘
FROM = ‘email0@Host.com‘
TO = ‘email1@Host.com,email2@Host.com‘
CREDENTIALS = (‘email0@Host.com‘,‘email0passwd‘)
SUBJECT = ‘Critical Event From [Project Name]‘
# Setup logging
logging.basicConfig(level=logging.INFO)
handler = handlers.SMTPHandler(HOST, FROM, TO, SUBJECT,CREDENTIALS)
email_logger = logging.getLogger(‘Critical email log‘)
email_logger.addHandler(handler)
email_logger.setLevel = logging.CRITICAL
return email_logger
def test():
log_file = "project_name.log"
my_logger = logger(log_file, "project_name")
my_logger.info(‘this is a test‘)
try:
open(‘/path/to/does/not/exist‘, ‘rb‘)
except Exception as e:
my_logger.error(‘Failed to open file‘, exc_info=True)
email_logger = critical_email_logger()
try:
email_logger.critical(‘Critical Event Notification~~~~~~‘)
except socket.error as error:
my_logger.critical(‘Could not send email via SMTPHandler: %r‘, error)
if __name__ == "__main__":
test()
以上是关于python logger的主要内容,如果未能解决你的问题,请参考以下文章