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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With