Logging: How to set the newline character of log files?

857 views Asked by At

I'm using logging on Python 3.7+ on both Windows and Linux, yet the line ending depends on the platform.

While you can set the newline character when reading or writing a file, obviously you cannot when setting a logging.FileHandler :

https://docs.python.org/3/library/logging.handlers.html#filehandler

Something like logging.FileHandler(newline = '\n') would do, as in io.open(newline = '\n') :

https://docs.python.org/3/library/io.html?highlight=file#io.open (reading or writing files)
https://docs.python.org/3/library/io.html?highlight=file#io.TextIOWrapper (newline explained here)

Perhaps there is a way to ensure the same line ending for logging on both Windows and Linux, but I found none yet.

Regards.

2

There are 2 answers

4
blues On BEST ANSWER

Unfortunately you don't have control over that, because open() which the FileHandler uses under the hood replaces newlines with the OS default. If you really want specific control over it, to create newlines that are different from the current OS default you have to subclass the FileHandler:

import logging

class MyFileHandler(logging.FileHandler):
    def _open(self):
        return open(self.baseFilename, self.mode, encoding=self.encoding, newline='\n') # set newline according to your needs here

h = MyFileHandler("foo.log")

edit: removed errors which didn't exist in 3.7

2
Michael Ruth On

logging.FileHandler inherits from logging.StreamHandler which has a terminator attribute. You may set it on the instance. I've provided a portable solution using the os module, but you may set it explicitly if desired.

import logging
h = logging.FileHandler("foo.log")
h.terminator = "\n"

edit: Fixed solution to always use \n as the line terminator.

https://docs.python.org/3/library/logging.handlers.html#logging.StreamHandler.terminator