Skip to main content

No project description provided

Project description

logargparser

Utility for the common case of managing logs from the command line in simple utilities.

Sample usage

In a python script called sample.py:

import logging
from logargparser import LoggingArgumentParser
        
logger = logging.getLogger(__name__)
        
def main():
    # Instead of the normal `parser = argparse.ArgumentParser.
    parser = LoggingArgumentParser(logger)
        
    # Add as many other arguments as you want.
    parser.add_argument('-o', "--output")
        
    args = parser.parse_args()
        
    logger.info("The logger was set up for us based on --log and/or --logfile command line args.")
        
    if args.output is not None:
        # Do something....
        pass
        
        
if __name__ == "__main__":
    main()

We can then invoke the script from the command line. First, to get help on all args:

python -m sample -h

The output will be:

usage: sample.py [-h] [--log {DEBUG,INFO,WARNING,ERROR,CRITICAL}]
                 [--logfile LOGFILE] [-o OUTPUT]

options:
  -h, --help            show this help message and exit
  --log {DEBUG,INFO,WARNING,ERROR,CRITICAL}
                        Logging level.
  --logfile LOGFILE     Optional file path that logs should be appended to.
                        The file will be created if it does not exist.
  -o OUTPUT, --output OUTPUT

Notice that everything worked like a normal script using argparse.ArgParser, but in addition to the -o/--output argument we created ourselves, there are two other arguments --log and --logfile available.

We can use --log as follows:

python -m sample --log INFO

This will produce the output

INFO:__main__:The logger was set up for us based on --log and/or --logfile command line args.

Notice that this output appears on the standard error output. It is generated by the logger.info statement in the python code above.

If we want this output to be appended to a log file instead of being written to standard error, we can run

python -m sample --log INFO --logfile mylog.log

Now when we run it the output will go to the file we specifcied, just as the help said it would.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

logargparser-0.1.1.tar.gz (9.2 kB view hashes)

Uploaded Source

Built Distribution

logargparser-0.1.1-py3-none-any.whl (10.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page