Go Logger - Why we wrote our own
Tags: webdev, devops, showdev, go
Published: 2020-10-09 13:58:53

---
title: Go Logger - Why we wrote our own
published: true
date: 2020-11-08 13:58:00 UTC
tags: webdev, devops, showdev, go
cover_image: https://dglsparsons.github.io/img/remote/logs.jpg
canonical_url: https://dglsparsons.github.io/posts/why-we-wrote-our-own-logger/
---
<p>At Shaamazi, we created and open-sourced our logger: <a href="https://github.com/shamaazi/antilog">antilog</a>. We created this out of frustration at the other loggers available for Go. In our minds, they all fell short in at least one of several ways. We wanted a logger that was simple and easy to use. A logger that doesn't bring a mountain of dependencies. A logger that outputs structured logs. A logger where context can be built over time. And finally, a logger that doesn't have log-levels.</p> <p>Here I'll look at the following:</p> <ul> <li>Why we care about logging so much.</li> <li>What the current logging landscape for Go looks like.</li> <li>Why each of these fundamental features (structured logging, building context and no log-levels) are so important</li> <li>How popular alternatives fail to meet our needs.</li> </ul> <h2 id="why-we-care-about-logging-so-much">Why we care about logging so much <a class="direct-link" href="#why-we-care-about-logging-so-much">#</a></h2> <p>Our largest product is a charity system that automates donations during Ramadan. Over 100,000 people, in around 140 different countries, use this product. Despite this, our engineering team is tiny with two engineers working on this product. As a result, the ability to quickly and efficiently identify problems in our code through inspecting logs is crucial.</p> <h2 id="what-other-logs-are-there%3F">What other logs are there? <a class="direct-link" href="#what-other-logs-are-there%3F">#</a></h2> <p>Go's standard library provides a <a href="https://golang.org/pkg/log/">logger module</a>. Yet, this module is very minimal: it gives a series of functions that can be called to log text, but little else. There are some 'batteries included' logging frameworks, such as <a href="https://github.com/sirupsen/logrus">logrus</a>. Unfortunately, we wanted a middle ground between the two. Logrus provided too much customisability. It is very verbose to use, and has a significant footprint. However, the standard library wasn't able to provide all the features we wanted. A third alternative is the <a href="https://github.com/uber-go/zap">zap</a> logger created by Uber. This looks like a strong contender but adds a lot of complexity. It has far more configuration with its various logger types (Sugar, Production, Development, etc.). There is also a <code>Sync()</code> function, a mix of <code>sprintf</code> and structured logging, and log-levels.</p> <p>Other alternatives do exist, but we could not find one that met our criteria.</p> <h2 id="structured-logging">Structured Logging <a class="direct-link" href="#structured-logging">#</a></h2> <p>Structured logging is the idea that logs should be more than a string message. They should also be able to embed and display structured information. There are two approaches to this: using a human-readable <a href="https://brandur.org/logfmt">logfmt</a> format, or, writing logs out as JSON. Logfmt has it's advantages; it is arguably more human-readable at an initial glance. However, most tools for searching through logs, such as Splunk, Kibana or CloudWatch, provide support for JSON logs. JSON is easier for programs to read and query and also allows complex datatypes to be expressed in logs. In our case, we are writing logs into CloudWatch. CloudWatch provides explicit support for querying JSON logs. As a result, we are <strong>only</strong> interested in writing JSON.</p> <p><img src="https://dglsparsons.github.io/img/cloudwatch-logs.jpg" alt="What our (test) logs look like in cloudwatch"></p> <p>The ideal would be for any logger to output JSON by default. Some loggers, such as zap, meet this need. Of the main two most popular contenders, the standard library and logrus, both fall short. The standard library doesn't provide structured logging at all. Logrus does but requires some small amount of config to achieve this (<code>logrus.SetFormatter(&amp;logrus.JSONFormatter{})</code>). This configuration is only a single line of code, but it is easy to miss when writing a new application, script or tool.</p> <p>Supporting many output formats is another pitfall. This adds more complexity to the logger, making it bulkier than we would like (in both binary size and CPU time). Instead, a logger that outputs JSON by default with no configuration required is ideal. antilog can be used straight out of the box, it requires no configuration at all.</p> <h2 id="building-context">Building Context <a class="direct-link" href="#building-context">#</a></h2> <p>As part of our logging, we want the ability to build up of information in logs over the lifecycle of an operation. To get a full picture of what is happening in our logs, we need to be able to provide context to any messages. To illustrate this point, here is a pretty rubbish log message that could show an issue parsing data:</p> <pre class="language-json"><code class="language-json"><span class="token punctuation">{</span> <span class="token property">"timestamp"</span><span class="token operator">:</span> <span class="token string">"2019-11-18T14:00:32Z"</span><span class="token punctuation">,</span> <span class="token property">"message"</span><span class="token operator">:</span> <span class="token string">"unable to parse json"</span> <span class="token punctuation">}</span></code></pre> <p>We can't easily identify what is going on here: is this an application issue? is it expected? What's causing it? By adding a small amount of context we can immediately glean much more information from our logs:</p> <pre class="language-json"><code class="language-json"><span class="token punctuation">{</span> <span class="token property">"timestamp"</span><span class="token operator">:</span> <span class="token string">"2019-11-18T14:00:32Z"</span><span class="token punctuation">,</span> <span class="token property">"message"</span><span class="token operator">:</span> <span class="token string">"unable to parse json"</span><span class="token punctuation">,</span> <span class="token property">"path"</span><span class="token operator">:</span> <span class="token string">"/api/signup"</span><span class="token punctuation">,</span> <span class="token property">"method"</span><span class="token operator">:</span> <span class="token string">"POST"</span><span class="token punctuation">,</span> <span class="token property">"status"</span><span class="token operator">:</span> <span class="token number">400</span><span class="token punctuation">,</span> <span class="token property">"request_id"</span><span class="token operator">:</span> <span class="token string">"1234abc"</span><span class="token punctuation">}</span></code></pre> <p>We can now see that it's an API endpoint for signup this happened at. From the 400 response, we can assume that this is due to a user submitting bad data rather than an error in our system. From a small amount of context, a previously meaningless log message becomes valuable.</p> <p>Unless we have a messy codebase, the places where want to write logs don't necessarily have access to all the information we might want. We don't want polluting to our code by passing <code>path</code>, <code>method</code>, <code>request_id</code> and many other fields around. We want the ability to attach these to our logger, building up the eventual output one piece at a time.</p> <p>In antilog we can build up an output by passing the logger around (or attaching it to context, if you've done much Go):</p> <pre class="language-go"><code class="language-go"> logger <span class="token operator">:=</span> antilog<span class="token punctuation">.</span><span class="token function">With</span><span class="token punctuation">(</span><br> <span class="token string">"common"</span><span class="token punctuation">,</span> <span class="token string">"this is a common field"</span><span class="token punctuation">,</span><br> <span class="token string">"other"</span><span class="token punctuation">,</span> <span class="token string">"I also should be logged always"</span><span class="token punctuation">)</span><br><br> logger<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token string">"I'll be logged with common and other field"</span><span class="token punctuation">)</span><br> logger<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token string">"Me too"</span><span class="token punctuation">)</span></code></pre> <h2 id="no-log-levels">No Log levels <a class="direct-link" href="#no-log-levels">#</a></h2> <p>A lack of log-levels seems like an oversight for a logging library. However, I strongly believe they aren't necessary and just complicate matters. Dave Cheney argues the same on <a href="https://dave.cheney.net/2015/11/05/lets-talk-about-logging">his blog</a>. This can be broken down by reasoning about each different log level:</p> <p><strong>Warning:</strong></p> <p>Warning messages fall into one of two categories:</p> <ul> <li>warnings you can ignore</li> <li>warnings you can't ignore</li> </ul> <p>Warnings that you can ignore are interesting. By definition, nothing has gone wrong. As such, they are no different to info level logs. Warnings that you can't ignore show the opposite: they are errors that are not logged at the correct level. As it is impossible to have a warning that does not fit into these two categories, warning as a log level is useless.</p> <p><strong>Error:</strong></p> <p>A similar approach removes the need for errors. Errors fall into one of two categories:</p> <ul> <li>Errors that you are handling (and recovering from)</li> <li>Errors that you are not handling.</li> </ul> <p>If you are handling the error, then the application will continue as expected, and the log line is only informational. If you are not handling the error, then you should not be logging it. It is the responsibility of the calling code to manage this error. As it is impossible to have an error that does not fit into these categories, the error log level is also useless.</p> <p><strong>Info:</strong></p> <p>Now there are no more warnings and errors, we have a single log-level: info. By itself, this is no different to not having any log levels at all. Instead, we have 'things we should log' and 'things we shouldn't log'.</p> <p>This argument to remove log levels can extend further. Log-levels are an attempt to provide a measure of how useful a particular message is. This is a flawed approach as the usefulness can't be determined when the message is written. This is because we do not know why our future selves may be looking at logs. It could be to diagnose a particular race condition, to fix a bug, or to track user behaviour. Without knowing why we will be looking at logs, it is impossible to determine what information is going to be the most relevant. Any attempt to predict is just noise. As a result, log-levels are a fruitless task.</p> <p>In the context of antilog, we wanted to avoid the typical <code>log.Info</code>, <code>log.Warn</code> and <code>log.Error</code> interfaces most loggers use. This leads to forced decision-making that is not productive. I've been on the end of one-too-many arguments over whether a log should be <code>Info</code> or <code>Warn</code> (see also <a href="https://en.wiktionary.org/wiki/bikeshedding">bikeshedding</a>). Most logging libraries do not give this freedom of thinking, and instead, force you to decide. We, contrastingly, provide just a <code>Write</code> method. Either <code>Write</code> your logs or don't.</p> <h2 id="in-conclusion">In Conclusion <a class="direct-link" href="#in-conclusion">#</a></h2> <p>The current logging landscape for Go was lacking. Existing libraries overcomplicated the process of writing logs by falling into one of four traps:</p> <ul> <li>forcing the use of log-levels;</li> <li>lacking structured logging;</li> <li>not allowing context to be built</li> <li>and allowing too much configuration.</li> </ul> <p>We sought a solution to these problems by creating our logging library, <a href="https://github.com/shamaazi/antilog">antilog</a>. We've been using it for around a year now and love it.</p><p>Thanks for reading. If you enjoyed this article, please share or   <a href="https://twitter.com/intent/follow?screen_name=dglsparsons" target="_blank" rel="noopener">follow me on twitter.</a></p>