1.2 A simple example 1.3 Logging to a file # assuming loglevel is bound to the string value obtained from the # command line argument. Convert to upper case to allow the user to # specify --log=DEBUG or --log=debug numeric_level =getattr(logging, loglevel .upper(), None ) if not isinstance(numeric_level, int): 3 (continues on next page) to get the value which you’ll pass to$_{basicConfig()}$ via the level argument. You may want to error check any user input value, perhaps as in the following example: getattr(logging, loglevel .upper()) and you have the value of the parameter passed for$_{--log}$ in some variable loglevel , you can use: --log=INFO If you want to set the logging level from a command-line option such as: This example also shows how you can set the logging level which acts as the threshold for tracking. In this case, because we set the threshold to$_{DEBUG}$, all of the messages were printed. DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too ERROR:root:And non-ASCII stuff, too, like Øresund and Malmö import logging logging.basicConfig(filename ='example.log ', encoding ='utf-8 ', level =logging.DEBUG) logging.debug( 'This message should go to the log file') logging.info('So should this ') logging.warning( 'And this, too') logging.error('And non-ASCII stuff, too, like Øresund and Malmö ') import logging logging.warning( 'Watch out!') # will print a message to the console logging.info('I told you so') # will not print anything A very simple example is: If you type these lines into a script and run it, you’ll see: WARNING:root:Watch out! printed out on the console. The$_{INFO}$ message doesn’t appear because the default level is$_{WARNING}$ . The printed message includes the indication of the level and the description of the event provided in the logging call, i.e. ‘Watch out!’. Don’t worry about the ‘root’ part for now: it will be explained later. The actual output can be formatted quite flexibly if you need that; formatting options will also be explained later. A very common situation is that of recording logging events in a file, so let’s look at that next. Be sure to try the following in a newly-started Python interpreter, and don’t just continue from the session described above: Changed in version 3.9: The encoding argument was added. In earlier Python versions, or if not specified, the encoding used is the default value used by$_{open()}$ . While not shown in the above example, an errors argument can also now be passed, which determines how encoding errors are handled. For available values and the default, see the documentation for$_{open()}$ . And now if we open the file and look at what we have, we should find the log messages: