logging to file #1309
-
HI, First of all, thank you for this wonderful library, I have been using Rich for several scripts now and it is wonderful. I really like the Rich handle for logging. I was wondering if there is a simple way to direct the logging with Rich to file output without printing out to console. For, what I am doing is: # Set logger using Rich: https://rich.readthedocs.io/en/latest/logging.html
logging.basicConfig(
level="INFO",
format="%(message)s",
datefmt="[%X]",
handlers=[RichHandler(rich_tracebacks=True)]
)
log = logging.getLogger("rich")
# Create handlers
LOG_FILE.unlink(missing_ok=True) # Remove old log file, otherwise new log info is appended
f_handler = logging.FileHandler(LOG_FILE)
f_handler.setLevel(logging.DEBUG)
# Create formatters and add it to handlers
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
f_handler.setFormatter(f_format)
# Add handlers to the logger
log.addHandler(f_handler) and while the code above works, it also prints the logging to console as well. I feel like I am missing something extremely simple here. Thank you so much! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can construct a Console with a file. console = Console(file=open('log.txt')) And then you can pass the console to the handler. RichHandler(console=console) |
Beta Was this translation helpful? Give feedback.
You can construct a Console with a file.
And then you can pass the console to the handler.