pfalcon / pycopy-lib

Standard library of the Pycopy project, minimalist and light-weight Python language implementation
https://github.com/pfalcon/pycopy
Other
246 stars 70 forks source link

logging: FileHandler writes to file only after closing the file #56

Closed balobinp closed 4 years ago

balobinp commented 4 years ago

Dear All, I'm using MicroPython v1.12 on ESP8266. When I'm trying to write logs with logging to file, the file is empty untill I close the file.

Example:

MicroPython v1.12 on 2019-12-20; ESP module with ESP8266 Type "help()" for more information.

import os import logging logger = logging.getLogger("testlogger") logger.setLevel(logging.DEBUG) fmt = logging.Formatter('%(asctime)s;%(name)s;%(levelname)s;%(message)s') os.remove("fh.log") fh = logging.FileHandler("fh.log") fh.setFormatter(fmt) logger.addHandler(fh) logger.debug('Level 1. Debug message') os.stat('fh.log')[6] 0 fh.close() os.stat('fh.log')[6] 56

A simple WA here can be rewriting FileHandler class in _init.py like this:

class FileHandler(Handler): def init(self, filename, mode="a", encoding=None, delay=False): super().init()

    self.encoding = encoding
    self.mode = mode
    self.delay = delay
    self.terminator = "\n"
    self.filename = filename

def emit(self, record):
    with open(self.filename, self.mode) as f:
        f.write(self.formatter.format(record) + self.terminator)

Example with the new init.py:

MicroPython v1.12 on 2019-12-20; ESP module with ESP8266 Type "help()" for more information.

import os import logging logger = logging.getLogger("testlogger") logger.setLevel(logging.DEBUG) fmt = logging.Formatter('%(asctime)s;%(name)s;%(levelname)s;%(message)s') os.remove("fh.log") fh = logging.FileHandler("fh.log") fh.setFormatter(fmt) logger.addHandler(fh) logger.debug('Level 1. Debug message') os.stat('fh.log')[6] 56

Best Regards, Pavel Balobin

pfalcon commented 4 years ago

It's a bit hard to see what exact issue is being reported here. If it's "In CPython, logging module flushes underlying stream after each logging entry, while pycopy-lib module didn't", then ack, and it was fixed in pycopy-logging 0.7.2.