简体   繁体   中英

How to print some statement to console while all others messages will be redirected to a log file?

I need to use a shell script to run python file and save all python script output to a log file. Below is a sample shell script:

#!/bin/bash
python script.py > logFile.log 2>&1

However, I need to print some statements in python script out to a console. For example, if the python script contains two print statements similar to below, the log file generated from the shell script will contain both statements, and I would like to also print statement2 to console.

print("statement1")
print("statement2") # also want to print this statement to console

I have tried using python logging module, but could not get it to work.

Thanks,

You should really use the logging module for this.

Try the following:

import logging

# Logging
log = logging.getLogger("log")
log2 = logging.getLogger("log2")
log.setLevel(logging.DEBUG)
log2.setLevel(logging.DEBUG)
format = logging.Formatter(fmt = "%(asctime)s - %(module)s - %(levelname)s: %(message)s", datefmt = "%d-%m-%Y %H:%M")

# For first file
logfile = logging.FileHandler("file.log")
logfile.setFormatter(format)
log.addHandler(logfile)

# For second file
logfile2 = logging.FileHandler("file2.log")
logfile2.setFormatter(format)
log2.addHandler(logfile2)

log.debug("test")
log2.debug("test2")

This creates two file handlers which can be used with log and log2 .

Produces two files in the current folder: file.log and file2.log .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM