Make the logger the first static field in a class
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
Format Specifiers
Log messages can use any of Java’s printf format specifiers; such as %s, %d, %016x etc.
Related: Preconditions only accepts the %s placeholder in error message strings
Avoid doing work at log sites
// Don't
atFine().log("stats=%s", createSummaryOf(stats));
logger.// Do
atFine().log("stats=%s", LazyArgs.lazy(() -> createSummaryOf(stats))); logger.
Don’t create a Throwable just to log it:
- when no Throwable exists
// Don't
atInfo().withCause(new Exception()).log("Message");
logger.// Do
atInfo().withStackTrace(<SIZE>).log("Message"); logger.
Consider rate limiting warnings which can be triggered by bad user input.
atWarning().every(100).log("message ...")
logger.atWarning().atMostEvery(30, SECONDS).log("message ...") logger.
Don’t log and throw
Sometime we want to add extra log before rethrow same exception:
- we can do as following, but don’t use
withCause(e)
as it would cause duplicate stacktrace.
catch (TheException e) {
atWarning().log("more context");
logger.throw e;
}
Other flogger Tips
- Don’t be afraid to add fine-grained logging to your code
- Use string literals for log messages and avoid string concatenation
- Don’t log and throw
- Don’t split log statements
- Avoid String.format in code that is frequently processed
- Every time String.format() is called, it uses a regular expression to parse the format String
flogger Implementation
- No varargs arrays are created (up to 10 parameters) and no auto-boxing is necessary (up to 2 parameters).
private static final class NoOp extends LoggingApi.NoOp<Api> implements Api {}
static final NoOp NO_OP = new NoOp();