Basic Usage
Log a line#
We may just log a line within class methods, extension methods, or package
functions. l is an extension method attached to all classes.
To get a log reference in package function, we declare it in the Kotlin source file.
Log tags are automatically generated for each of the example above, which is unique to the class in context.
The logging action is as simple as it could possibly be. We don't need to
declare anything besides import, because it is
implemented as Kotlin extensions and delegate properties.. When method
testOfLog is executed, the following log line is sent to the following can be
observed in logcat.
where HeWo is an automatically generated log tag. It is an abbreviation of the class HelloWorld.
Code to log for other severity levels are similar
In some case if we want to specify the tag explicitly. We could just do that right away
Multi-line text#
Log content with multiple lines will be broken down.
will generate log like this:
Logging exception#
We have seen log with error level:
We may also log Throwable object directly:
Stacktrace of the exception is generated and logged line-by-line
Filtering log#
We may filter log by log severity level anytime.
It take effect from the next log invocation.
THe severity is in the increasing order of the following:
- Trace
- Debug
- Info
- Warn
- Error
- Fatal
Log with Lambda#
When we have the capability of filtering logs, we start to worry that our log invocation peform unnecessary work. For example,
Sometimes, it may be costly to construct the string for log, and we don't want to pay the price
if the logLevel property filtered the log.
We may use lambda to defer the processing of the log content:
Then the actual evaluation of the string is deferred until it is needed. No cost is paid for filtered log.
Dump file to log#
We may dump a file to log easily.
The content of file My-file.txt will be write to log, one line per log line.
To avoid overwhelming underlying log. The function limit the maximum size of file write to underlying log. Default is 4KB. We may change this by providing maximum size parameter (in bytes):