How to tell YAML to always create a log file in a project folder using dictConfig?

In my Python program, I have the following code:

def main():
    # The file path
    path = os.path.dirname(os.path.realpath(__file__))
    ...
    # Config file relative to this file
    loggingConf = open('{0}/configs/logging.yml'.format(path), 'r')
    logging.config.dictConfig(yaml.load(loggingConf))
    loggingConf.close()
    logger = logging.getLogger(LOGGER)
    ...

and this is my logging.yml configuration file:

version: 1
formatters:
  default:
    format: '%(asctime)s %(levelname)s %(name)s %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: default
    stream: ext://sys.stdout
  file:
    class : logging.FileHandler
    formatter: default
    filename: bot.log
loggers:
  cloaked_chatter:
    level: DEBUG
    handlers: [console, file]
    propagate: no

The problem is that the bot.log file is created where the program is running. I want it to always be created in the project folder, i.e. In the same folder as my Python program.

For example, running the program with ./bot.pywill create a log file in the same folder. But running with python3 path/bot.pywill create a log file above the Python program in the file hierarchy.

How can I write the file name in the configuration file to solve this problem? Or do I need to write my own handler? If so, how? Or is it impossible to solve with dictConfig?

+5
1

, . , :

import os
import yaml

def logmaker():
    path = os.path.dirname(os.path.realpath(__file__))
    path = os.path.join(path, 'bot.log')
    return logging.FileHandler(path)

def main():
    # The file path
    path = os.path.dirname(os.path.realpath(__file__))

    # Config file relative to this file
    loggingConf = open('{0}/logging.yml'.format(path), 'r')
    logging.config.dictConfig(yaml.load(loggingConf))
    loggingConf.close()
    logger = logging.getLogger('cloaked_chatter')
    logger.debug('Hello, world!')

if __name__ == '__main__':
    main()

, logging.yml, script. logmaker - . YAML :

version: 1
formatters:
  default:
    format: '%(asctime)s %(levelname)s %(name)s %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: default
    stream: ext://sys.stdout
  file:
    () : __main__.logmaker
    formatter: default
loggers:
  cloaked_chatter:
    level: DEBUG
    handlers: [console, file]
    propagate: no

Python script, , bot.log script YAML. bot.log:

2013-04-16 11:08:11,178 DEBUG cloaked_chatter Hello, world!

N.B. script , .

: () , value , .

+5

All Articles