Python Tutorial: Logging Advanced - Loggers, Handlers, and Formatters
Why Stack Overflow recommends it
Stack Overflow users link it when explaining how Python loggers, handlers and formatters fit together, especially per-module loggers and routing output to both console and file.
Recommended by 1 people across 1 different months, 2020 to 2020.
What it is
A Python tutorial by Corey Schafer covering the more advanced parts of the standard logging module: creating loggers, attaching handlers, and customizing formatters. It follows his basics logging video and uses a code walkthrough with sample code on GitHub.
What people said
Recommends Aya · 2020-11 · Stack Overflow · on “Is there any way to stop logger in the AWS Iot Python SDK?”
I dont know if it recommended, but I did it: sdk_logger = logging.getLogger('AWSIoTPythonSDK.core.protocol.mqtt_core') sdk_logger.setLevel(logging.WARNING) you can see here an example that they printed it to a different file: [LINK] this is a very simple explanation on how logging works in general when you import a module (If you need) [this video] credit: How do I define a different logger for an imported module in Python? [LINK]
Cites positive.definite · 2020-04 · Stack Overflow · on “In python I can write a log to console but its not getting written into file”
Create an new logger with desired stream & file handlers: import logger, sys logger = logging.Logger('AmazeballsLogger') #Stream/console output logger.handler = logging.StreamHandler(sys.stdout) logger.handler.setLevel(logging.WARNING) formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") logger.handler.setFormatter(formatter) logger.addHandler(self.handler) #File output fh = logging.FileHandler("test.log") fh.setLevel(logging.DEBUG) fh.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")) logger.addHandler(fh) And you're ready to take it for a spin: print(logger.handlers) logger.critical("critical") logger.error("error") logger.warning(
Cites Mr. Hobo · 2020-12 · Stack Overflow · on “What is the advantage of using Flasks app.logger?”
Setting logger = logging.getLogger(__name__) configures your root logger by default, which you might not want in a production environment. For instance when you define a logger per file/module then you might fall into a trap like the one explained here [this video] . So as explained and commented by @noslenkwah. Having an internal logger is not unique to Flask, it's the standard way to use logging in Python. Every module defines it's own logger, but the configuration of the logging is only handled by the last link in the chain: your project. My point - if you have a small application, you can obviously stick to a default logger. For more control over the application and setting more than one logg