Package: python-zerolog
zerologPython logging with zero setup JSON output.To keep the code base and the API simple, zerolog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient)zerolog.ConsoleWriter.Getting startedSimple Logging Examplefromzerologimportloglog.print("Hello, World!")# {"level":"debug","time":"2023-12-14T23:23:57.922Z","message":"Hello, World!"}Note: By default log writes tosys.stderr.bufferand the default log level forlog.printisdebug.Leveled LoggingSimple Leveled Logging Examplefromzerologimportloglog.info().msg("Hello, World!")# {"level":"info","time":"2023-12-14T23:36:47.768Z","message":"Hello, World!"}Contextual Loggingfromzerologimportloglog.debug().str("scale","kg").float("weight",42.69).msg("measuring in kilogram")log.debug().str("Name","Olivier").send()# {"level":"debug","scale":"kg","weight":42.69,"time":"2023-12-14T23:32:26.368Z","message":"measuring in kilogram"}# {"level":"debug","Name":"Olivier","time":"2023-12-14T23:32:26.368Z"}Exception LoggingYou can log exceptions using theexcmethod.fromzerologimportlogtry:1/0exceptExceptionase:log.exc(e).msg("uh oh")# {"level":"error","exception":"division by zero","time":"2023-12-14T23:59:04.061Z","message":"uh oh"}Note: The default field name for exceptions isexception, you can change this by settingzerolog.ExceptionFieldNameto meet your needs.Exception Logging with Stack Traceimportzerologfromzerologimportlog,stacktracedefmain():zerolog.ExceptionStackMarshaler=stacktrace.marshal_stacktry:outer()exceptExceptionase:log.error().stack().exc(e).msg("uh oh")definner():1/0defmiddle():inner()defouter():middle()# {"level":"error","stack":[{"source": "/app/test.py", "line": "9", "func": "main"}, {"source": "/app/test.py", "line": "23", "func": "outer"}, {"source": "/app/test.py", "line": "19", "func": "middle"}, {"source": "/app/test.py", "line": "15", "func": "inner"}],"exception":"division by zero","time":"2023-12-15T00:28:04.255Z","message":"uh oh"}Note:zerolog.ExceptionStackMarshalermust be set in order forstackto output anything.Logging Fatal Messagesfromzerologimportloglog.fatal().msg("this is very bad")# {"level":"fatal","time":"2023-12-15T00:22:03.664Z","message":"this is very bad"}# exit status 1Pretty loggingTo log a human-friendly, colorized output, usezerolog.ConsoleWriter:importzerologfromzerologimportlogzerolog.GlobalLogger=log.output(zerolog.ConsoleWriter(out=sys.stderr.buffer))log.info().str("foo","bar").msg("Hello World")# 10:18PM INF Hello World foo=barTo customize the configuration and formatting:importzerologoutput=zerolog.ConsoleWriter(out=sys.stdout.buffer,time_format=zerolog.TimeFormatRFC3339)output.format_level=lambdai:f"|{i:6s}|".upper()output.format_message=lambdai:f"***{i}****"output.format_field_name=lambdai:f"{i}:"output.format_field_value=lambdai:f"{i}".upper()log=zerolog.new(output).ctx().timestamp().logger()log.info().str("foo","bar").msg("Hello World")# 2023-12-23T23:11:48Z | INFO  | ***Hello World**** foo:BARLog Samplingimportzerologfromzerologimportlogsampled=log.sample(zerolog.BasicSampler(n=10))sampled.info().msg("will be logged every 10 messages")# {"level":"info","time":"2023-12-22T21:34:15.205Z","message":"will be logged every 10 messages"}More advanced sampling:importzerologfromzerologimportlog# Will let 5 debug messages per period of 1 second.# Over 5 debug message, 1 every 100 debug messages are logged.# Other levels are not sampled.sampled=log.sample(zerolog.LevelSampler(debug_sampler=BurstSampler(burst=5,period=1,next_sampler=zerolog.BasicSampler(n=100))))sampled.debug().msg("hello world")# {"level":"debug","time":"2023-12-22T21:38:33.359Z","message":"hello world"}HooksimportzerologfromzerologimportlogclassSeverityHook:defrun(self,e:zerolog.Event,lvl:zerolog.Level,msg:str):iflvl!=zerolog.NoLevel:e.str("severity",lvl.string())hooked=log.hook(SeverityHook())hooked.warn().msg("")# {"level":"warn","time":"2023-12-22T21:44:48.157Z","severity":"warn"}Global SettingsSome settings can be changed and will be applied to all loggers:zerolog.GlobalLogger: You can set this value to customize the global logger (the one used by package level methods).zerolog.SetGlobalLevel: Can raise the minimum level of all loggers. Call this withzerolog.Disabledto disable logging altogether (quiet mode).zerolog.DisableSampling: If argument istrue, all sampled loggers will stop sampling and issue 100% of their log events.zerolog.TimestampFieldName: Can be set to customizetimestampfield name.zerolog.LevelFieldName: Can be set to customizelevelfield name.zerolog.LevelTraceValue: Can be set to customizetracelevel value.zerolog.LevelDebugValue: Can be set to customizedebuglevel value.zerolog.LevelInfoValue: Can be set to customizeinfolevel value.zerolog.LevelWarnValue: Can be set to customizewarnlevel value.zerolog.LevelErrorValue: Can be set to customizeerrorlevel value.zerolog.LevelFatalValue: Can be set to customizefatallevel value.zerolog.MessageFieldName: Can be set to customizemessagefield name.zerolog.ExceptionFieldName: Can be set to customizeexceptionfield name.zerolog.CallerFieldName: Can be set to customizecallerfield name.zerolog.CallerSkipFrameCount: Can be set to customize the number of stack frames to skip to find the caller.zerolog.CallerMarshalFunc: Can be set to customize global caller marshaling.zerolog.ExceptionStackFieldName: Can be set to customizestackfield name.zerolog.ExceptionStackMarshaler: Can be set to customize the function called to extract the stack from the exception if any.zerolog.ExceptionMarshalFunc: Can be set to customize global exception marshaling.zerolog.AnyMarshalFunc: Can be set to customize the function called foranymarshaling.zerolog.TimeFieldFormat: Can be set to customizetimefield value formatting. If set withzerolog.TimeFormatUnix,zerolog.TimeFormatUnixMsorzerolog.TimeFormatUnixMicro, times are formatted as a UNIX timestamp. If set tozerolog.TimeFormatRFC3339,zerolog.TimeFormatRFC3339Msorzerolog.TimeFormatRFC3339Microthe time is formatted as a RFC3339 date string.zerolog.TimestampFunc: Can be set to customize the function called to generate a timestamp.zerolog.ExceptionHandler: Called whenever zerolog fails to write an event on its output. If not set, an error is printed on the stderr. This handler must be thread safe and non-blocking.Field TypesStandard TypesstrboolintfloatAdvanced Fieldsexc: Takes anExceptionand renders it as a string using thezerolog.ExceptionFieldNamefield name.func: Runs a function only if the level is enabled.timestamp: Inserts a timestamp field withzerolog.TimestampFieldNamefield name, formatted usingzerolog.TimeFieldFormat.time: Adds a field with time formatted withzerolog.TimeFieldFormat.any: Useszerolog.AnyMarshalFuncto marshal the value.Most fields are also available in the list format (strsforList[str],boolsforList[bool]etc.)CreditsBased on the excellentzerologin Go.