2

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Kochise
  • 504
  • 5
  • 10

2 Answers2

2

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

Michael Ruth
  • 2,938
  • 1
  • 20
  • 27
  • Ok, I already tried `h.terminator = '\n'` but the line ending still is `\r\n` on **Windows**. – Kochise Sep 10 '21 at 09:17
  • @Kochise: `\r\n` is the correct line terminator for Windows text files. It probably doesn't do that on Lunix. – martineau Sep 10 '21 at 09:28
1

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

blues
  • 4,547
  • 3
  • 23
  • 39