@@ -53,11 +53,20 @@ def define_log_processors(self):
5353 """
5454 # these processors should accept logger, method_name and event_dict
5555 # and return a new dictionary which will be passed as event_dict to the next one.
56- return [
56+
57+ # NOTE if we are using a tty, then we must add our own timestamp.
58+ processors = []
59+
60+ if sys .stderr .isatty ():
61+ processors .append (structlog .processors .TimeStamper (fmt = "%Y-%m-%d %H:%M%S" ))
62+
63+ processors .extend ([
5764 structlog .stdlib .PositionalArgumentsFormatter (),
5865 structlog .processors .StackInfoRenderer (),
5966 structlog .processors .format_exc_info ,
60- ]
67+ ])
68+
69+ return processors
6170
6271 def define_log_renderer (self ):
6372 """
@@ -66,6 +75,16 @@ def define_log_renderer(self):
6675 # it must accept a logger, method_name and event_dict (just like processors)
6776 # but must return the rendered string, not a dictionary.
6877 # TODO tty logic
78+ if self .args .log_format == "json" :
79+ return structlog .processors .JSONRenderer ()
80+
81+ if self .args .log_format == "pretty" :
82+ return structlog .dev .ConsoleRenderer ()
83+
84+ # log format is None, we need to guess from the tty
85+ if sys .stderr .isatty ():
86+ return structlog .dev .ConsoleRenderer ()
87+
6988 return structlog .processors .JSONRenderer ()
7089
7190 def define_log_pre_format_hooks (self ):
@@ -117,7 +136,7 @@ def processor(logger, method_name, event_dict):
117136 structlog .configure (
118137 processors = processors ,
119138 context_class = dict ,
120- logger_factory = LevelLoggerFactory (level = level ),
139+ logger_factory = LevelLoggerFactory (stream = sys . stderr , level = level ),
121140 wrapper_class = BoundLevelLogger ,
122141 cache_logger_on_first_use = True ,
123142 )
@@ -161,6 +180,13 @@ def define_baseargs(self, parser):
161180 help = 'Name to identify this instance' )
162181 parser .add_argument ('--log-level' , default = self .LOG_LEVEL ,
163182 help = 'Logging level as picked from the logging module' )
183+ parser .add_argument ('--log-format' , default = None ,
184+ # TODO add more formats
185+ choices = ("json" , "pretty" ,),
186+ help = ("Force the format of the logs. By default, if the "
187+ "command is from a terminal, print colorful logs. "
188+ "Otherwise print json." ),
189+ )
164190
165191 def define_args (self , parser ):
166192 '''
0 commit comments