import logging
# log
logging.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)
# log
logger.debug('This is a debug message.') # ✔️✔️
logger.info('This is an informational message.') # ✔️✔️
logger.warning('This is a warning message.') # ✔️✔️
# =========================================================
# logger 2
logger_2 = logging.getLogger('my_logger_2')
logger_2.setLevel(logging.WARNING)
# log
logger_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 yaml
import logging
import logging.config
# 載入 configuration_file.conf,建立 logger
logging.config.fileConfig('logging.conf')
logger = logging.getLogger(__name__)
# 寫入 Log
logger.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,建立 logger
with open('logging.yaml', 'r') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
logger = logging.getLogger(__name__)
# 寫入 Log
logger.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')
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 logging
class LoggerFilter(logging.Filter):
def filter(self, record):
return record.levelno >= logging.WARNING
class HandlerFilter(logging.Filter):
def filter(self, record):
if record.msg.find('abc') == -1:
return True
return False
# 建立 Handler
logger = logging.getLogger('test')
logger.setLevel(logging.INFO)
# 建立 Handler
stream_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 log
logger.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 logging
def logger(func):
def wrapper(*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 result
return wrapper
logging.basicConfig(level=logging.INFO)
@logger
def adder(x, y):
return x + y
print(adder(10, 5))
執行結果:
INFO:root:Running "adder" with arguments (10, 5) and kwargs {}
INFO:root:adder returned 15
15
PYTHON
import logging
class LevelFilter(logging.Filter):
"""
This is a custom filter class that filters out log messages below certain level.
"""
def filter(self, record):
return record.levelno >= logging.INFO
def setup_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 logger
logger = setup_logger()
def logger_decorator(func):
def wrapper(*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 result
return wrapper
@logger_decorator
def adder(x, y):
return x + y
print(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