実装
同じ階層にmain.py
とlogger.py
があるとします。
logger.py
import logging
import logging.handlers
def set_logger():
logger = logging.getLogger()
streamHandler = logging.StreamHandler()
fileHandler = logging.handlers.RotatingFileHandler(
"./logs/app.log", maxBytes=1000000, backupCount=5, encoding="utf-8"
)
formatter = logging.Formatter(
'%(asctime)s| %(levelname)-5s | %(name)s.%(funcName)s.%(lineno)d | %(message)s'
)
streamHandler.setFormatter(formatter)
fileHandler.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
streamHandler.setLevel(logging.INFO)
fileHandler.setLevel(logging.DEBUG)
logger.addHandler(streamHandler)
logger.addHandler(fileHandler)
return logger
main.py
# 最初に定義
from logger import set_logger
if __name__ == "__main__":
set_logger()
...
..
.
各モジュールでの使用例
import logging
logger = logging.getLogger(__name__)
logger.debug("debug")
logger.info("info")
logger.warning("warn")
logger.error("error")
logger.critical("critical")
結果
コンソール
$ python /app/tmp/main.py
2024-10-25 13:22:45,521| INFO | functions.apicall_vad.54 | done: ./tmp/target.wav
2024-10-25 13:22:45,523| INFO | functions._clear_dir.241 | done: clear ./tmp_splitted_wav
2024-10-25 13:22:45,526| INFO | functions.split_wav_by_vad.132 | done: ./tmp_splitted_wav/0.wav
2024-10-25 13:22:45,527| INFO | functions.split_wav_by_vad.132 | done: ./tmp_splitted_wav/1.wav
app.log
2024-10-25 13:23:01,511| INFO | functions.apicall_asr.98 | done: ./tmp_combined_wav/2.wav
2024-10-25 13:23:07,337| DEBUG | functions.apicall_asr.89 | _json_data= {'data': ["brabrabra"], 'errors': []}