I would like to create log file for each iteration of my script. I am creating logger for each iteration and i need close this opened file at the end of iteration because if I am not, I will recieve error Too many open files.
formatter = logging.Formatter('%(asctime)s %(message)s')
handler = logging.FileHandler(logging_file)
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
handler.close()
This should work but I recieved SyntaxError:
File "start.py", line 73
handler.close()
^
SyntaxError: invalid syntax
How should I close file handlers at the end of iteration? I tried to create handler and close it immediately to be sure there is no problem that I added handler to logger before, but the problem persist:
handler = logging.FileHandler(logging_file)
handler.close()
Related
I have configured my logging to log both File & Stream.
I just want to see the print statements in my console & see other info on my log file (except unhandled exceptions as python shows them on the console by default)
I set the StreamLogging.setLevel(level=logging.CRITICAL) but it still shows API connection messages.
I want to get the Python's default stderr like before configuring the logging, but also change the output, like adding %(asctime)s before printing.
My Logging
import logging
FileLoggingFormat = f"%(message)s"
FileLoggingDate = r"%m/%d/%Y %H:%M:%S"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
# Add StreamHandler
StreamLogging = logging.StreamHandler()
logger.addHandler(StreamLogging)
StreamLogging.setFormatter(logging.Formatter("%(message)s"))
StreamLogging.setLevel(level=logging.CRITICAL)
# Add FileHandler
FileLogging = logging.FileHandler(
filename="Log.log",
mode="w",
encoding="utf-8"
)
logger.addHandler(FileLogging)
FileLogging.setFormatter(logging.Formatter(FileLoggingFormat, FileLoggingDate))
❌ Not suitable Result in Console
(Printed statements showed by 📝)
📝 Port: 1523
📝 NotFound.
INFO:library.connection.connection:Connecting...
Traceback (most recent call last):
File "c:\Users\test.py", line 20, in <module>
f.write(message)
TypeError: write() argument must be str
INFO:library.session.session:Session stopped
Session stopped
✅ Suitable Result in Console
(Only display prints & unhandled exceptions)
📝 Port: 1523
📝 NotFound.
Traceback (most recent call last):
File "c:\Users\test.py", line 20, in <module>
f.write(message)
TypeError: write() argument must be str
✅ Suitable Result in Console
(Only display prints & unhandled exceptions with date, added %(asctime)s to StreamHandler)
2022/10/22 10:16:03.678
📝 Port: 1523
2022/10/22 10:16:03.700
📝 NotFound.
2022/10/22 10:16:03.706
Traceback (most recent call last):
File "c:\Users\test.py", line 20, in <module>
f.write(message)
TypeError: write() argument must be str
There are several things that need explaining:
Using logging.basicConfig
You use logging.basicConfig(level=logging.INFO). That has for effect to create a StreamHandler and attach it to the root logger (the one you are using since logger = getLogger() and getLogger() with no argument returns the "root" logger).
At the end of your logging setup, if you do:
print(logger, logger.handlers)
It will give:
<RootLogger root (INFO)> [<StreamHandler <stderr> (NOTSET)>, <StreamHandler <stderr> (CRITICAL)>, <FileHandler /home/vvvvv/Log.log (NOTSET)>]
You have 2 StreamHandler instead of just 1. Moreover, the superfluous StreamHandler has a logging level of NOTSET meaning it will log everything. This is the cause of your bug.
You could solve it by removing this line:
logging.basicConfig(level=logging.INFO)
Doing so, gives
<RootLogger root (INFO)> [<StreamHandler <stderr> (CRITICAL)>, <FileHandler /home/vvvvv/Log.log (NOTSET)>]
Using a child logger instead of the root logger
As previously said, you are using the root logger (logger = logging.getLogger()). You should refrain from doing so and instead use a child logger, like this:
# logger = logging.getLogger()
logger = logging.getLogger("foobar")
logger.propagate = False
Set propagate to False to avoid sending the logs upwards to the root logger.
Piecing everything together gives the correct behavior:
import logging
FileLoggingFormat = f"%(message)s"
FileLoggingDate = r"%m/%d/%Y %H:%M:%S"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("foobar")
logger.propagate = False
# Add StreamHandler
StreamLogging = logging.StreamHandler()
StreamLogging.setFormatter(logging.Formatter("%(message)s"))
StreamLogging.setLevel(level=logging.CRITICAL)
logger.addHandler(StreamLogging)
# Add FileHandler
FileLogging = logging.FileHandler(
filename="Log.log",
mode="w",
encoding="utf-8"
)
logger.addHandler(FileLogging)
FileLogging.setFormatter(
logging.Formatter(FileLoggingFormat, FileLoggingDate)
)
I am trying to change the default behaviour of the logging module so that it adds a prefix string to each log level.
logging.basicConfig(level=logging.INFO, format='%(message)s', filename='output.log', filemode='w')
console = logging.StreamHandler()
logging.getLogger('').addHandler(console) # add the handler to the root logger
log = logging.getLogger(__name__)
log.info("this is an info")
log.error("this is an error")
log.warning("this is a warning")
I want
log.error("this is an error")
to print:
Error: this is an error
Or, the following line,
log.warning("this is a warning")
to print:
Warning: this is a warning
Error prefix in red and warning prefix in yellow.
Is there any non-hacky way to do this?
I am trying to write custom handler for logging that would send logs to netcat
I can see on the receiving end that the connection is established and then closes, however, no messages are received and i can see no errors.
here is the code i am running
import socket
import time
import logging
hostname = '127.0.0.1'
port = '1234'
message = 'hello world!\n'
class Nc_handler(logging.Handler):
def __init__(self, hostname, port):
logging.Handler.__init__(self)
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((hostname, int(port)))
def emit(self, content):
log_entry = self.format(content)
print("Checking if emit is run")
self.socket.send(log_entry.encode())
logger = logging.getLogger(__name__)
# set format
nc_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
# create nc handler
nc_handler = Nc_handler(hostname, port)
# set handler's level
nc_handler.setLevel(logging.INFO)
# set handler's format
nc_handler.setFormatter(nc_format)
logger.addHandler(nc_handler)
logger.info(message)
If i use nc_handler.emit('Hello') it throws an error:
File "handler.py", line 35, in <module>
nc_handler.emit(message)
File "handler.py", line 17, in emit
log_entry = self.format(content)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 869, in format
return fmt.format(record)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 608, in format
record.message = record.getMessage()
AttributeError: 'str' object has no attribute 'getMessage'
So i suspect i don't use Formatter correctly but I can't figure out what exactly I am doing wrong.
I would really appreciate any help or advice.
Method emit has a wrong signature: its argument must be a LogRecord object. Not a string.
That is because format method needs a LogRecord object.
That is the cause of the AttributeError exception.
I see also a confusion I don't understand: why using message as argument for logging.info?
message is an attribute of the LogRecord object too and is taken from what you logged explicitly.
Use a hard-coded string:
logging.info("Hello")
Or use a different variable:
myvar = "Hello"
logging.info(myvar)
Does it help?
I created a small function to setup logging, with a filehandler for 'everything', and smtphandler for error and above. Error logs write to the log file and send correctly to email, but debug, info, notset don't, even though setlevel is set to 0 for filehandler. Why's that? Code below
#logsetup.py
import logging
import logging.handlers
def _setup_logger(name, log_file):
"""Function to setup logger"""
logger = logging.getLogger(name)
#Create Formatters
file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
mail_formatter = logging.Formatter('%(name)s - %(message)s')
#Create handler, set formatting, set log level
file_handler_obj = logging.FileHandler(log_file)
file_handler_obj.setFormatter(file_formatter)
file_handler_obj.setLevel(0)
#Create handler, set formatting, set log level
smtp_handler_obj = logging.handlers.SMTPHandler(mailhost=('smtp.gmail.com', 587),
fromaddr='mymail#example.com',
toaddrs='mymail#example.com',
subject='Error in Script',
credentials=('mymail#example.com', 'pwexample'), #username, password
secure=())
smtp_handler_obj.setFormatter(mail_formatter)
smtp_handler_obj.setLevel(logging.ERROR)
# add the handlers to logger
logger.addHandler(smtp_handler_obj)
logger.addHandler(file_handler_obj)
return logger
#mytest.py
import time
import logsetup
if __name__ == '__main__':
TEST_SETTINGS = config_funcs._get_config('TEST_SETTINGS')
logtime = time.strftime('%Y%m%d') # -%H%M%S")
log = logsetup._setup_logger('TEST', TEST_SETTINGS['logging_dir'] + 'Py_Log_%s.log' % logtime)
log.error('Writes to log file and sends email')
log.debug('Supposed to write to log file, does nothing.')
Apparently, logging needs it's own logging level aside from the handlers. Setting logger.setLevel(logging.DEBUG) right before returning logger causes it to work correctly. Documentation says
When a logger is created, the level is set to NOTSET (which causes all
messages to be processed when the logger is the root logger, or
delegation to the parent when the logger is a non-root logger). Note
that the root logger is created with level WARNING.
Which means that if the handlers are lower level than the root logger (which ERROR is not, but DEBUG is) then the handlers which I guess is a child because I'm getting a named logger? Not quite sure on the why of it, but that does 'fix' it, in case anyone comes to this later.
It seems that on a couple machines I'm getting double output like this:
INFO LED NOTIFICATION STARTED
INFO:output_logger:LED NOTIFICATION STARTED
This is the function I'm using:
def setup_logger(name, log_file, level=logging.INFO, ContentFormat='%(asctime)s %(levelname)s %(message)s', DateTimeFormat="%Y-%m-%d %H:%M:%S", CreateConsoleLogger=False):
"""Function setup as many loggers as you want"""
logger = logging.getLogger(name)
logger.setLevel(level)
if CreateConsoleLogger:
# create console handler
handler = logging.StreamHandler()
handler.setLevel(level)
formatter = logging.Formatter("%(levelname)s %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# create a file handler
handler = RotatingFileHandler(log_file, maxBytes=2000000, backupCount=5)
handler.setLevel(level)
formatter = logging.Formatter(ContentFormat, DateTimeFormat)
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
This is how I'm creating the logger:
output_logger = setup_logger('output_logger', 'log/autofy.log', level=logging.DEBUG, CreateConsoleLogger=True)
And this is how I call it:
output_logger.info("LED NOTIFICATION STARTED")
On a most of computers I just see the same message printed to the console that's saved to the file as expected ("INFO LED NOTIFICATION STARTED"), but on other computers it's doing this weird double output thing. My code is exactly the same from one computer to another, so any ideas what could be causing this on some computers and not others?
EDIT
I'm writing the script using notepad++ and running it in a terminal window on an Ubuntu 16.04 machine. I'm using python3.
Try adding this to your code:
logging._get_logger().propagate = False