1

I am using a logger in my Python 2.7 code to create a CSV to plot. It is running on an embedded module without an RTC. I don't have any use for a timestamp, but would like to include a label, so I can plot them easier. The logger is set up in such a way that it continues between reboots.

I am currently logging with a formatter providing a label like this:

# Add formatter to the file handler.
formatter = logging.Formatter('%(asctime)s,%(message)s','%H:%M:%S')
fh.setFormatter(formatter)

but as the board does not have an RTC would like to just log the line number as a label instead of the time.

How to go about this? I can not just have an incremental integer as the next time the program starts it will start from scratch instead of increment.

Thanks in advance!

maaark
  • 11
  • 1
  • Without knowledge of whether your system has any form of non-volatile storage it is not possible to answer. However if it does, then the answer is as straightforward as storing the sequence number in non-volatile storage. If your logging is to a persistent file, then you might simply inspect the last log message in the file to initialise the counter. – Clifford Jan 26 '18 at 07:47
  • Thanks @Clifford! The latter is what I am looking for: how do I inspect the last log message to initialise the counter? Is this something I do from the logger, or just by doing [something like this?](https://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python) – maaark Jan 26 '18 at 09:46
  • I am no expert in Python or Linux - only here because you tagged it "embedded". The logger class does not provide a means to _read_ the log, which is reasonable since the log need not be persistent (i.e. to a file). You will have to use regular file I/O I guess. It would be most efficient perhaps to seek to the end of the file and iterate backward to find the start of the last line given that the logs are variable length - of place the sequence number at the end rather than start of the line perhaps. – Clifford Jan 26 '18 at 09:54
  • Thanks @Clifford! I'll do it like that, then :) – maaark Jan 26 '18 at 16:55

1 Answers1

0

To display the current line of code in the logger output, this could be your answer

import logging
from inspect import currentframe, getframeinfo


logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(line)s - %(message)s')

logger = logging.getLogger()

logger.debug('Hi', extra={'line': getframeinfo(currentframe()).lineno})

If you want to display, the line number of an opened file or CVS, you can change the value in extra dictionary to an appropriate attribute.

Please, do not forget to include extra dictionary in all the debug statements.

Cheers! :)

BinaryMonster
  • 1,118
  • 7
  • 10
  • That is not what he was asking. He wants to label the _log line_ with a sequence number that is monotonic through a reset. – Clifford Jan 26 '18 at 07:43