import logger code example
Example 1: python logging to file
import logging
"""
DEBUG
INFO
WARNING
ERROR
CRITICAL
"""
# asctime: time of the log was printed out
# levelname: name of the log
# datefmt: format the time of the log
# give DEBUG log
logging.basicConfig(format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%d-%m-%Y:%H:%M:%S',
level=logging.DEBUG,
filename='logs.txt')
logger = logging.getLogger('my_app')
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred")
Example 2: logging.logger
import logging
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.debug("some debugging...")
logger.error("some error...")
Example 3: python fme logger
logger = fmeobjects.FMELogFile()
logger.logMessageString("{}".format('Error'), fmeobjects.FME_ERROR)
Example 4: python logging basiclogging rotatingfilehandler
import logging
rfh = logging.handlers.RotatingFileHandler(
filename='foo.log',
mode='a',
maxBytes=20*1024*1024,
backupCount=2,
encoding=None,
delay=0
)
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(name)-25s %(levelname)-8s %(message)s",
datefmt="%y-%m-%d %H:%M:%S",
handlers=[
rfh
]
)
logger = logging.getLogger('main')
logger.debug("test")
Example 5: from logging import logger
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
logger.debug('Loging %s lewel', 'DEBUG')
logger.info('Loging %s lewel', 'INFO')
logger.warning('Loging %s lewel', 'WARN')
logger.error('Loging %s lewel', 'ERROR')
logger.critical('Loging %s lewel', 'CRITICAL')
Example 6: pythong logging logger to string
import logging
try:
from cStringIO import StringIO # Python 2
except ImportError:
from io import StringIO
class LevelFilter(logging.Filter):
def __init__(self, levels):
self.levels = levels
def filter(self, record):
return record.levelno in self.levels
log_stream = StringIO()
logging.basicConfig(stream=log_stream, level=logging.NOTSET)
logging.getLogger().addFilter(LevelFilter((logging.INFO, logging.WARNING, logging.ERROR)))
logging.info('hello world')
logging.warning('be careful!')
logging.debug("you won't see this")
logging.error('you will see this')
logging.critical('critical is no longer logged!')
print(log_stream.getvalue())