Pasha
Pasha

Reputation: 190

python logging debug to file errors to stdout

Is there any way in python logging module to send info & errors to stdout and debug to file. Some commands in my script produce a long output which I don't want to send to stdout.

I am using the following logging function which writes logs to file and stdout

def mylog(release_num, logdir='/tmp'):
    applog = logging.getLogger()
    applog.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s", "%b %d %Y %H:%M:%S")

    logfile = "{}/{}.log".format(logdir, release_num)

    if not os.path.exists(logdir):
        os.makedirs(logdir)

    fileHandler = logging.FileHandler(logfile, 'ab')
    fileHandler.setLevel(logging.DEBUG)
    fileHandler.setFormatter(formatter)
    applog.addHandler(fileHandler)

    cformat = logging.Formatter("[%(levelname)8s] : %(message)s")
    consoleHandler = logging.StreamHandler(sys.stdout)
    consoleHandler.setFormatter(cformat)
    log.addHandler(consoleHandler)

    return applog

Upvotes: 1

Views: 468

Answers (1)

heemayl
heemayl

Reputation: 41987

You need to set the loglevel of consoleHandler to logging.INFO to log messages of level info or higher through the handler:

consoleHandler.setLevel(logging.INFO)

Upvotes: 2

Related Questions