Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Configure logger with yaml to open logfile in write mode

I have the following configuration of a logger in a the file loggingConfig.yml

version: 1
disable_existing_loggers: False
    formatters:
        simple:
            format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

handlers:
    console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout

file_handler:
    class: logging.FileHandler
    level: INFO
    formatter: simple
    filename: info.log
    encoding: utf8

loggers:
    my_module:
        level: ERROR
        handlers: [console]
        propagate: no

root:
     level: INFO
     handlers: [console, file_handler]

And the following python code:

import logging
import logging.config
import yaml

with open('loggingConfig.yml', 'rt') as f:
    config = yaml.safe_load(f.read())
    logging.config.dictConfig(config)

logger = logging.getLogger(__name__)

logger.info('TestLogger')

This works fine, but now I would like to open the logfile in write mode and not in append mode. I wasn't able to find any example which use a yaml file and opens the logfile in write mode.

I only found, that open in write mode can be done using the fileConfig

logging.config.fileConfig('logging.conf')

and specify args in the logging.conf file:

args=('info.log', 'w')

Is there any way how I can do this using the yaml file or manipulating the config in the sourcecode?

like image 717
Dave Avatar asked Apr 10 '18 11:04

Dave


People also ask

What does logger getLogger do Python?

The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not. Multiple calls to getLogger() with the same name will return a reference to the same logger object.

How do you use logger INFO in Python?

Configuring Logging Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above. Creating a logging config file and reading it using the fileConfig() function. Creating a dictionary of configuration information and passing it to the dictConfig() function.


1 Answers

Try using the following configuration:

file_handler:
    class: logging.FileHandler
    level: INFO
    formatter: simple
    filename: info.log
    encoding: utf8
    mode: w

The default mode is 'a' which means append . More info on that here

like image 116
ma3oun Avatar answered Sep 21 '22 18:09

ma3oun