python 自定义log模块

  1. 随便用用1
import logging
# logging.basicConfig(level=logging.ERROR, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s:%(message)s')
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s:%(message)s')
logger = logging.getLogger(__name__)

logger.info('infor')
logger.error('errof')
  1. 随便用用2
###############################################
#### LOGGING CLASS SETTINGS (py25+, py30+) ####
###############################################
import socket
import glob
import logging
import logging.handlers
import telnetlib
import time

Sus = 'succesfully'
tn = telnetlib.Telnet('localhost','9999')
print '...telnet pass'
time.sleep(1)
tn.write ('xxx')
tn.read_until(Sus )
tn.write ('quit\n')
print '...quit\n'

#f1 = logging.Formatter(fmt='%(levelname)s:%(name)s: %(message)s '
#	'(%(asctime)s; %(filename)s:%(lineno)d)',
#	datefmt="%Y-%m-%d %H:%M:%S")

handlers = [
    logging.handlers.RotatingFileHandler('rotatedSyslog.log', maxBytes=10000000, backupCount=2),  #file_handler
    logging.StreamHandler()  #console_handler
]
syslog_logger = logging.getLogger()
syslog_logger.setLevel(logging.DEBUG)

for h1 in handlers:
#	h1.setFormatter(f1)
	h1.setLevel(logging.DEBUG)
	syslog_logger.addHandler(h1)
	
##############################
#### END LOGGING SETTINGS ####
##############################


s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 8888))
while True:
	data, addr = s.recvfrom(2048)
	data.rstrip('\x00')
	syslog_logger.debug(data)
#	print data
	

  1. 定义 log.py
import logging
import logging.handlers

LOG_FILENAME = 'jd-assistant.log'

logger = logging.getLogger()

def set_logger():
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

    file_handler = logging.handlers.RotatingFileHandler(
        LOG_FILENAME, maxBytes=10485760, backupCount=5, encoding="utf-8")
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

set_logger()
  1. 使用
from log import logger

class AsstException(Exception):

    def __init__(self, message):
        super().__init__(message)
        logger.error(message)
posted @ 2020-10-04 11:15  该显示昵称已被使用了  阅读(210)  评论(0编辑  收藏  举报