Search code examples
pythonloggingnewlineeolos-agnostic

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


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.


Solution

  • 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