import logging# loglogging.info("[This is a info]")logging.warning("[This is a warning]")logging.error("[This is a error]")logging.critical("[This is a critical]")
執行結果
WARNING:root:[This is a warning]
ERROR:root:[This is a error]
CRITICAL:root:[This is a critical]
'''basicConfig ->logger ->logger'''import logging# 設定多個屬性logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')# =========================================================# logger 1 logger = logging.getLogger('my_logger_1')logger.setLevel(logging.DEBUG)# loglogger.debug('This is a debug message.')# ✔️✔️logger.info('This is an informational message.')# ✔️✔️logger.warning('This is a warning message.')# ✔️✔️# =========================================================# logger 2logger_2 = logging.getLogger('my_logger_2')logger_2.setLevel(logging.WARNING)# loglogger_2.debug('This is a debug message.')logger_2.info('This is an informational message.')logger_2.warning('This is a warning message.')# ✔️✔️
執行結果:
app.log
2023-07-19 18:18:20,495 - DEBUG - This is a debug message.
2023-07-19 18:18:20,495 - INFO - This is an informational message.
2023-07-19 18:18:20,495 - WARNING - This is a warning message.
2023-07-19 18:18:20,495 - WARNING - This is a warning message.
import yamlimport loggingimport logging.config# 載入 configuration_file.conf,建立 loggerlogging.config.fileConfig('logging.conf')logger = logging.getLogger(__name__)# 寫入 Loglogger.debug('This is a debug message')logger.info('This is an info message')logger.warning('This is a warning message')logger.error('This is an error message')# =========================================================# 載入 configuration_file.yaml,建立 loggerwithopen('logging.yaml', 'r')as f: config = yaml.safe_load(f.read()) logging.config.dictConfig(config)logger = logging.getLogger(__name__)# 寫入 Loglogger.debug('This is a debug message')logger.info('This is an info message')logger.warning('This is a warning message')logger.error('This is an error message')
logger
PYTHON
'''getLogger('my_logger') ->FileHandler'''import logging# 建立 loggerlogger = logging.getLogger('my_logger')logger.setLevel(logging.DEBUG)# 建立 FileHandlerfile_handler = logging.FileHandler('app.log')formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')file_handler.setLevel(logging.INFO)file_handler.setFormatter(formatter)# 加入 handlerlogger.addHandler(file_handler)# 寫入 loglogger.info('This is an informational message.')logger.warning('This is a warning message.')
執行結果:
app.log
2023-07-19 17:58:12,393 - INFO - This is an informational message.
2023-07-19 17:58:12,393 - WARNING - This is a warning message.
PYTHON
'''getLogger(__name__) ->FileHandler'''import logging# 建立 loggerlogger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)formatter = logging.Formatter('%(name)s - %(asctime)s - %(levelname)s - %(message)s')# 建立 FileHandlerfile_handler = logging.FileHandler('app.log')file_handler.setLevel(logging.WARNING)file_handler.setFormatter(formatter)# 加入 handlerlogger.addHandler(file_handler)# loglogger.debug('This is a debug message')logger.info('This is an info message')logger.warning('This is a warning message')logger.error('This is an error message')
執行結果:
app.log
__main__ - 2023-07-19 18:01:14,806 - WARNING - This is a warning message
__main__ - 2023-07-19 18:01:14,806 - ERROR - This is an error message
Handler
PYTHON
import logging# 設定多個屬性logger = logging.getLogger('my_logger')logger.setLevel(logging.DEBUG)formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')# =========================================================# 建立 FileHandlerfile_handler = logging.FileHandler('app.log')file_handler.setLevel(logging.INFO)file_handler.setFormatter(formatter)# =========================================================# 建立 StreamHandlerconsole_handler = logging.StreamHandler()console_handler.setLevel(logging.DEBUG)console_handler.setFormatter(formatter)# =========================================================# 加入 handlerlogger.addHandler(file_handler)logger.addHandler(console_handler)# =========================================================# 寫入 loglogger.debug('This is a debug message.')logger.info('This is an informational message.')logger.warning('This is a warning message.')
執行結果:
2023-07-19 18:04:38,094 - DEBUG - This is a debug message.
2023-07-19 18:04:38,094 - INFO - This is an informational message.
2023-07-19 18:04:38,094 - WARNING - This is a warning message.
app.log
2023-07-19 18:04:38,094 - INFO - This is an informational message.
2023-07-19 18:04:38,094 - WARNING - This is a warning message.
Filter
PYTHON
import loggingclassLoggerFilter(logging.Filter):deffilter(self,record):return record.levelno >= logging.WARNINGclassHandlerFilter(logging.Filter):deffilter(self,record):if record.msg.find('abc')==-1:returnTruereturnFalse# 建立 Handlerlogger = logging.getLogger('test')logger.setLevel(logging.INFO)# 建立 Handlerstream_handler = logging.StreamHandler()logger.addHandler(stream_handler)# =========================================================logger.warning('this is warning-1')# ✔️✔️logger.info('this is info-1')# ✔️✔️# =========================================================logger.addFilter(LoggerFilter())logger.warning('this is warning-2')# ✔️✔️logger.info('this is info-2')# Skip this log# =========================================================stream_handler.addFilter(HandlerFilter())logger.warning('this is warning-3')# ✔️✔️logger.info('this is info-3')# Skip this loglogger.warning('this is warning-abc')# Skip this log
執行結果:
this is warning-1
this is info-1
this is warning-2
this is warning-3
Logger Decorator
PYTHON
import loggingdeflogger(func):defwrapper(*args,**kwargs): logging.info(f"Running \"{func.__name__}\" with arguments {args} and kwargs {kwargs}") result =func(*args, **kwargs) logging.info(f"{func.__name__} returned {result}")return resultreturn wrapperlogging.basicConfig(level=logging.INFO)@loggerdefadder(x,y):return x + yprint(adder(10, 5))
執行結果:
INFO:root:Running "adder" with arguments (10, 5) and kwargs {}
INFO:root:adder returned 15
15
PYTHON
import loggingclassLevelFilter(logging.Filter):""" This is a custom filter class that filters out log messages below certain level. """deffilter(self,record):return record.levelno >= logging.INFOdefsetup_logger(): logger = logging.getLogger('custom_logger') logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# Create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.INFO) ch.setFormatter(formatter) logger.addHandler(ch)# Create file handler which logs even debug messages fh = logging.FileHandler('log_file.log') fh.setLevel(logging.INFO) fh.setFormatter(formatter) logger.addHandler(fh)# Add filter to the logger logger.addFilter(LevelFilter())return loggerlogger =setup_logger()deflogger_decorator(func):defwrapper(*args,**kwargs): logger.info(f"Running \"{func.__name__}\" with arguments {args} and kwargs {kwargs}") result =func(*args, **kwargs) logger.info(f"{func.__name__} returned {result}")return resultreturn wrapper@logger_decoratordefadder(x,y):return x + yprint(adder(10, 5))
執行結果:
2023-07-19 18:40:51,589 - custom_logger - INFO - Running "adder" with arguments (10, 5) and kwargs {}
2023-07-19 18:40:51,589 - custom_logger - INFO - adder returned 15
15