Google Flogger Best Practices


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.

Avoid doing work at log sites

// Don't
logger.atFine().log("stats=%s", createSummaryOf(stats));
// Do
logger.atFine().log("stats=%s", LazyArgs.lazy(() -> createSummaryOf(stats)));

Don’t create a Throwable just to log it:

  • when no Throwable exists
// Don't
logger.atInfo().withCause(new Exception()).log("Message");
// Do
logger.atInfo().withStackTrace(<SIZE>).log("Message");

Consider rate limiting warnings which can be triggered by bad user input.

logger.atWarning().every(100).log("message ...")
logger.atWarning().atMostEvery(30, SECONDS).log("message ...")

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) {
  logger.atWarning().log("more context");
  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();

Resource

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)