LoginSignup
0
1

[備忘録]Python YAML ログ 書き方

Posted at

pyファイル

import logging

class Common:
    config: dict
    logger: logging.Logger

    def __init__(self):
        config_file = load_yaml('./basic.yaml')
        self.config = load_yaml(config_file['configuration_file'])
        filename = "xxx"
        create_dir(os.path.dirname(filename))
        logging.basicConfig(
            filename=filename,
            level=get_log_level(self.config['log']['level']),
            format=self.config['log']['format']
        )
        self.logger = logging.getLogger()

    
    # 設定ファイルのパスを取得する
    def get_filepath(dirname: str, filename: str) -> os.path:
        return os.path.abspath(os.path.join(os.path.dirname(__file__), f'./{dirname}/{filename}'))
    
    # yaml を読み込む
    def load_yaml(filename: str) -> dict:
        file_path: str = get_filepath(dirname='configures', filename=filename)
        try:
            with Path(file_path).open('r', encoding='utf-8') as stream:
                return yaml.full_load(stream)
        except FileNotFoundError:
            print(f'{file_path} が見つかりません。')
            raise
    
    # ディレクトリを作成する
    def create_dir(dirname: str) -> None:
        os.makedirs(dirname, exist_ok=True)

    # ログレベルを返す
    #   指定が非対応の場合は DEBUG
    def get_log_level(level: str) -> int:
        if level == 'info':
            return logging.INFO
        elif level == 'warn':
            return logging.WARN
        elif level == 'error':
            return logging.ERROR
        return logging.DEBUG

yamlファイル

# ログ出力に関連する設定
log:
  # ログ出力先ディレクトリ
  #   app からの相対パスまたは絶対パスで記述すること
  dir: './log'
  # ログ・ファイル名
  #   datetime の書式に従うこと
  filename: '%Y-%m-%d.log'
  # ログ書式
  #   logging の書式に従うこと
  format: '%(asctime)s:%(levelname)s:%(message)s'
  # ログレベル
  #   'debug', 'info', 'warn', 'error' に対応
  level: 'debug'
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1