2

The answer to this question implies that Python logs are flushed with every write.

My experience with Python 3.8.1 on Windows 10 is that there is some buffering happening.

I have implemented very simple logging based on the tutorial

import logging
<snip - other setup>
logging.basicConfig(filename='MyLog.txt', level=logging.DEBUG)

while True:
    <snip - get the data>
    if newdata == 1 :    
        print ("> ",DataString,sep='')
        logging.info(datettime_string+' '+DataString)

New data appears once every several minutes, which prints and logs one line of text. As I watch the console output, and compare that to the logging file, I see a significant delay (several data updates) before the log file is updated. Is there a way I can set the logging file to unbuffered, or explicitly flush the log file?

tim11g
  • 1,935
  • 5
  • 27
  • 41
  • 1
    The other question clearly shows that it flushes the Python stream. If it's not working, it seems like an OS problem. – Barmar May 31 '21 at 19:07
  • How are you checking the log file, maybe the problem is there. – Barmar May 31 '21 at 19:11
  • I'm using Notepad++ to monitor the log file. It has a mechanism (File Stats Auto-detection) to reload changed files. It does re-load changed file immediately when the application gains focus. – tim11g May 31 '21 at 19:18
  • I suspect the issue is with the 'if newdata ==1'. I've confirmed your setup otherwise. I'm running under Windows 10, using Notepad++. – Jeremy Whitcher May 31 '21 at 21:56
  • @Jeremy - The `print ("> ",DataString,sep='')` statement is working and printing the data at the exact moment it is available. Only the `logging.info` is delayed. If the `newdata==1` was not working, then the `print` statement would not be executed either. – tim11g Jun 01 '21 at 15:49

0 Answers0