How can I setup python's module logging so that every line it prints to the file starts with a specific string?
            Asked
            
        
        
            Active
            
        
            Viewed 247 times
        
    0
            
            
         
    
    
        Konrad Rudolph
        
- 530,221
- 131
- 937
- 1,214
 
    
    
        Sky
        
- 379
- 3
- 13
- 
                    2Refer [How to ask mcve](https://stackoverflow.com/help/minimal-reproducible-example) – Sociopath Sep 30 '19 at 08:52
- 
                    Possible duplicate of [How to write to a file, using the logging Python module?](https://stackoverflow.com/questions/6386698/how-to-write-to-a-file-using-the-logging-python-module) – Hampus Larsson Sep 30 '19 at 08:57
2 Answers
1
            You can do this via the log formatter. Here's a simple example configuring it via logging.basicConfig:
import logging
logging.basicConfig(format="Hello at %(asctime)s %(message)s: %(levelname)s")
logging.warning("world")
 
    
    
        Joe Halliwell
        
- 1,155
- 6
- 21
- 
                    So this makes sense, thanks. But the string that I want to print is the time of printing. So how can I make the 'hello' be a variable? – Sky Sep 30 '19 at 09:10
- 
                    Ah, well check the documentation. But I'll add a timestamp to my example. – Joe Halliwell Sep 30 '19 at 09:16
0
            
            
        Using python logging
Formatting the Output
You can pass any variable that can be represented as a string from your program as a message to your logs. If you for example want to log the process ID along with the level and message, you can do something like this:
import logging
logging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')
logging.warning('This is a Warning')
# Output:
# 18472-WARNING-This is a Warning
For further details see documentation on realpython.
 
    
    
        mrk
        
- 8,059
- 3
- 56
- 78