Skip to content

Commit 4649256

Browse files
committed
Add -o option to CLI and file logger
1 parent aead633 commit 4649256

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

auto_comment_plus.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import copy
88
import logging
99
import random
10+
import sys
1011
import time
1112

1213
import jieba.analyse
@@ -571,6 +572,7 @@ def main(opts=None):
571572
parser.add_argument('--log-level',
572573
help='specify logging level (default: info)',
573574
default='INFO')
575+
parser.add_argument('-o', '--log-file', help='specify logging file')
574576
args = parser.parse_args()
575577
if args.log_level.upper() not in [
576578
'DEBUG', 'WARN', 'INFO', 'ERROR', 'FATAL'
@@ -586,6 +588,10 @@ def main(opts=None):
586588
'dry_run': args.dry_run,
587589
'log_level': args.log_level
588590
}
591+
if hasattr(args, 'log_file'):
592+
opts['log_file'] = args.log_file
593+
else:
594+
opts['log_file'] = None
589595

590596
# logging on console
591597
_logging_level = getattr(logging, opts['log_level'])
@@ -598,6 +604,7 @@ def main(opts=None):
598604
# controling characters. When it comes to file logger, the number should
599605
# set to 8.
600606
formatter = StyleFormatter('%(asctime)s %(levelname)-19s %(message)s')
607+
rawformatter = StyleFormatter('%(asctime)s %(levelname)-8s %(message)s', use_style=False)
601608
console = logging.StreamHandler()
602609
console.setLevel(_logging_level)
603610
console.setFormatter(formatter)
@@ -606,6 +613,18 @@ def main(opts=None):
606613

607614
logger.debug('Successfully set up console logger')
608615
logger.debug('CLI arguments: %s', args)
616+
logger.debug('Opening the log file')
617+
if opts['log_file']:
618+
try:
619+
handler = logging.FileHandler(opts['log_file'])
620+
except Exception as e:
621+
logger.error('Failed to open the file handler')
622+
logger.error('Error message: %s', e)
623+
sys.exit(1)
624+
handler.setLevel(_logging_level)
625+
handler.setFormatter(rawformatter)
626+
logger.addHandler(handler)
627+
logger.debug('Successfully set up file logger')
609628
logger.debug('Options passed to functions: %s', opts)
610629
logger.debug('Builtin constants:')
611630
logger.debug(' CONFIG_PATH: %s', CONFIG_PATH)

0 commit comments

Comments
 (0)