Skip to content
ImagineWorld

Monitoring Application Logs

node_idnode-book_the-software-developer-s-guide-to-linux_chapter-14-monitoring-application-logs
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleMonitoring Application Logs
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 14 — Monitoring Application Logs

Section titled “Chapter 14 — Monitoring Application Logs”

Welcome to the world of Linux logging! As software developers, understanding logging in Linux, especially with tools like systemd and journald, is crucial. Here’s a breakdown of what you need to know.

Logs are records of events happening in a software application or operating system. It’s a flexible format and unique to each application, but how logs are processed, stored, and retrieved is more uniform on modern systems. It’s essential for you to understand logs as a developer because the logs you can access in Linux provide insights into the behavior of the operating system and all applications running on it. You’ll use this knowledge to understand errors, track application performance, and debug. Logs are your first line of defense in troubleshooting, so prepare to get comfortable with them.

In this chapter, we’ll give you an overview of Unix and Linux logging, and show you the most common ways that software developers interact with logs. You’ll see:

  • How logs are emitted by the system and applications running on it
  • Where logs are collected on most modern Linux systems
  • Some historical knowledge about how logging worked in the past, which still comes in handy on many production systems you’ll run into
  • How to find and view logs when you’re troubleshooting an application
  • How logs are being centralized at companies and when services are deployed in cloud environments

We’ll also give a few tips on getting the most out of structured logging while avoiding some common pitfalls that developers often fall into.

As we saw in the introduction, logs are simply informational messages – records of events happening in a software application or operating system. Like many Unix concepts, there are few hard and fast rules: if you write a two-line script that writes a timestamp into a text file, that might count as a log. Some logs are simple plaintext strings sent to well-known file locations on the system, and others are highly structured binary data managed exclusively by a daemon such as systemd.

As a developer, you’re probably familiar with log levels, which are labels that indicate the urgency of events on your software. Think “error,” “info,” and “debug” messages, which you’ve surely seen scrolling past in the terminal while developing software. We’ll cover these common log levels later, but for now, you should be aware of three main sources of logs in a modern, full-featured Linux environment: system, service, and non-service application logs. The source of the log can give you important contextual information about what’s happening in a specific log message.

System logs are logs sent by the operating system (“the kernel”) itself. These include errors, messages about hardware events, resource consumption and limits, configuration and security, and noteworthy changes in the system state.

Service logs are emitted by the services running on a system. Specifically on Linux, they are emitted by the services managed by the systemd init system, which do their logging through a service called journald. They can provide insights into the health and status of various services.

On the systems you’re likely to encounter, system and service logs are both commingled in journald. We’ll learn all about systemd and journald (and journalctl) as we progress through this chapter.

Non-systemd-managed applications are the outliers that don’t generally log through journald. You’ll have to find their log files via documentation for each application, although well-behaved applications usually write their own log files in a directory like /var/log/$APPLICATION_NAME/, where $APPLICATION_NAME is the name of the application.

As we go through this chapter, the importance of understanding journald and journalctl commands will become apparent. However, before we go into that, we should note a few details about Linux logging.

You’ve seen by now that Unix-like systems are tremendously flexible. If you don’t like the default way that things are done, you can break with convention and configure things to work the way you want.

This is also a tremendous downside when you’re learning the basics of Unix and Linux. Many things – from software configuration to default user settings – can be configured in many different ways, and there’s no way to know what the convention is in a new environment except to ask (and sometimes, troubleshoot).

Nowhere is that truer than when it comes to logging, which has been especially affected by the recent shifts in how companies do their computing. Logging was done a certain way for decades, when most companies directly purchased, configured, and managed long-lived physical servers with a single OS installed on them. As workloads have shifted to the cloud, and things have shifted to many operating systems per physical machine (VMs) and even many environments per OS (containers), traditional ideas of how logging should work have shifted as well.

That’s all to say that when it comes to figuring out logging in a new job or team, the question is not, “How is logging done on Linux?” but rather, “How is logging currently done here?” It really depends on decisions made by the developers of the software you’re using. When learning about logging in this chapter, we advise that you keep this in mind.

While, in most situations, services will log either through a library or by simply writing to stdout, Unix-like systems provide a command that logs to a syslog server. We’ll look at what that means below. Since both syslogd and systemd provide a syslog server no matter what kind of system you are using, there is a unified command to send a log message:

logger Hello World!

This will log Hello World. The logger command has many options, and it can be a valuable tool when debugging any issues, when wanting to log in a shell script, or when explaining how logging works.

When a system uses systemd, journald takes over the logging side. When you’re troubleshooting a Linux machine running systemd, this is the first place you should be looking for logs. By default, journald captures all output from supervised processes. Anything emitted on stderr is treated as an error. So, unless the software is configured or hardcoded to log to a location that’s not stderr/stdout, you will find the logs in the systemd journal.

Logs logged to journald can be queried via the journalctl command. It provides a means to query based on individual services, time, and system restarts and allows one to use options similar to the tail command. Let’s jump in and get some practice using journalctl.

The basics of working with journalctl are simple. Think about it; when you’re troubleshooting an application, what do you need to be able to do with its logs?

First, you’ll want to be able to find and view the current set of logs. journalctl will give you that, but you’ll quickly realize you didn’t actually want all the logs, just the most recent ones. So, let’s filter with the -n flag.

To get a look at the last 100 log messages in journald, try this command:

journalctl –n 100

This will print out the last 100 lines logged to the system. You will notice that this is similar to the tail command explained earlier in this book. If you followed along, these lines will likely contain the “Hello World!” message from above.

You might also want to see logs in real time. For example, following your application logs during startup can help you see exactly when things go wrong:

journalctl -fu unitname

The -f flag stands for “follow,” and the -u flag stands for “unit” – the system unit (or “service”) that you want to filter logs for.

Even when you filter down to a specific unit that you’re interested in, you may still be overwhelmed by the number of logs that match. Filtering by time can be useful here, especially when you are trying to correlate a known external problem (outage, error, and so on) to the application logs from that moment in time forward. Use --since and --until for this:

journalctl --since "2021-01-01 00:00:00"

You can also use some shorthand for this, like today:

journalctl --until today

You can also use –until to set an end time for your filter and mix these up to get pretty specific. For example:

journalctl --since "2021-01-01 00:00:00" --until "1 hour ago"

Note

One caveat to viewing and filtering logs by time is that you’ll almost always want to use the --utc option for journalctl, which displays timestamps in UTC. When you’re helping an ops team troubleshoot an outage, this is almost exclusively done using UTC times to prevent timezone-related confusion.

There are additional filters for things like user/group ID.

If you know you’re looking for an error, you can tell journalctl to show you only errors (or any of the other log levels listed at https://wiki.archlinux.org/title/Systemd/Journal#Priority_level in descending order of criticality: emerg, alert, crit, err, warning, notice, info, debug):

journalctl -p err

Sometimes things get really wild, and a fault actually causes a reboot. In those cases, you’ll want to see logs from a previous boot of the system. You can view all available boots with --list-boots, like so:

journalctl --list-boots

Then select a specific boot from the list with the -b argument. In this case, we want the one labeled 2:

journalctl -b –2

By itself, the –b flag means “the current system boot.”

In the introduction, we mentioned that system-level log messages are sent by the operating system (“the kernel,” in Linux jargon). To see just those messages, use the --k (or --dmesg, for historical reasons) flag.

In a Docker container, the most common way to treat logs is to simply assume that the container’s main process is the one we want output from and that it’s logging to the standard output (stdout). Container orchestrators (that is, tools like Kubernetes and Nomad), as well as various cloud services that are responsible for executing containers, will assume stdout to be where relevant logs will go and, depending on the configuration, will forward it accordingly. We will go a bit more into this in the Centralized logging section below.

Compared to the systemd / journald logging we’ve shown you, syslog may seem a bit archaic. We prefer to think of it as having a storied history – although it’s been around since the 1980s, it’s still a useful, flexible, and widely-used logging tool. More importantly, you’re almost guaranteed to come across it on real production systems, so it’s worth knowing the basics to avoid being caught off guard during an outage where time is critical.

On a Unix-like system, logging to syslog is often equivalent to logging to a file in /var/log, with the majority of messages typically going to /var/log/messages. Keep in mind, however, that not everything you find in /var/log necessarily went through syslog. Various pieces of software also implement their own way of writing log files, skipping the syslog daemon entirely.

This works by syslog ingesting all the logs sent to it and depending on various parameters, like the facilities mentioned below, outputting them into a file. On virtually all systems, the default for this is /var/log/messages. If you followed along and your system uses syslog, then this is also where you’ll find the Hello World! message from above.

Syslog is a standardized protocol for logging. While, at the time of this writing, syslogd mostly deals with log lines, the current standard [RFC 5424] also allows for structured logging. However, since this isn’t widely supported, we will just briefly go over its basic concepts as a protocol for line/message-based logging. If you don’t interact with syslog at all, feel free to skip this section.

As mentioned earlier, syslog is a protocol. While it’s most frequently used for software, such as databases that want to log locally, production setups usually have a centralized logging server that logs are shipped to. Being only a protocol, various software (such as PostgreSQL, nginx, and so on) can emit logs using this protocol, and various logging-related software, like Logstash, Loki, syslogd, syslog-ng, and others can ingest its logs. It usually uses either port 514 (UDP) or port 6514 (TCP).

Since syslog is a very old protocol from the 1980s, some of its concepts might look archaic. It uses pre-defined facilities to specify the type of log message. Each facility has its own code:

  • 0: kern – Kernel messages.
  • 1: user – User-level messages. These are often used by processes.
  • 2: mail – Mail system. Mostly useful for mail servers, SMTP, IMAP, and POP3. Spam-related daemons and software usually log here.
  • 3: daemon – System daemons. Daemons, especially ones related to the OS (such as for NTP), log here.
  • 4: auth – Security/authentication messages. You will typically find login attempts, for example, locally, via SSH, but also for various other services here.
  • 5: syslog – Messages generated internally by syslogd. These will be messages related to syslog itself.
  • 6: lpr – Line printer subsystem. Printer-related logs.
  • 7: news – Network news subsystem. This is historical, and not typically used anymore.
  • 8: uucp – UUCP subsystem. This is historical, and not typically used anymore.
  • 9: cron – Cron subsystem. Logs related to cron jobs. These can be very useful for debugging cron jobs.
  • 10: authpriv – Security/authentication messages. This is similar to auth but is usually considered to be logged to a more restricted set of destinations. Most Linux software logs here instead of auth.
  • 11: ftp – FTP daemon. Mostly historical. Logs for FTP servers.
  • 12: ntp – NTP subsystem. Logs for the Network Time Protocol (NTP), so clock synchronization.
  • 13: security – Log audit. Security-related events.
  • 14: console – Log alert. Messages related to the “local console.”
  • 15: solaris-cron – Clock daemon.
  • 16 to 23: local0 to local7 – Locally used facilities, meaning local software. PostgreSQL, for example, logs to local0 per default when logging to syslog.

On many systems, you’ll find files in /var/log/ that are named similarly to these facilities. So, for example, if you need to debug a cron job on a system not using journald, you’ll likely find the output in /var/log/cron, /var/cron/log, /var/log/messages, or similar.

Keep in mind that what exactly is logged in each facility is not standardized. You will likely come across situations where different operating systems or similar software might not agree on which facility to log to.

This is a concept you are probably more familiar with. Messages come with a severity of one of seven different levels:

  • 0: emerg – Emergency
  • 0: alert – Alert
  • 0: crit – Critical
  • 0: err – Error
  • 0: warning – Warning
  • 0: notice – Notice
  • 0: info – Informational
  • 0: debug – Debug

As with facilities, what exactly constitutes each severity level depends on the software used.

Syslog has many implementations. These typically allow you to configure filtering, and save and forward messages based on facilities and severity levels. Some systems come with a service called syslogd, rsyslog, or syslog-ng, which can be configured in /etc/syslog.conf, /etc/syslog-ng/. Loki, Logstash, and other distributed log management tools have their own respective ways of configuring logging, usually in a three-fold structure, with one place to define input, another to filter and transform, and a third to store or forward the output.

Everyone does logging a bit differently and what is considered best practice can vary across projects and time. However, there are some things you should be aware of.

When using any kind of structured logging, try to make sure to share common keywords, such as request and user IDs, while also trying to avoid conflicting keywords used for similar, but not exactly the same, things. Depending on the backing database, you might also run into issues with types here, for example, in a situation where user might be the key for an integer, a string, or its own nested structure, like a JSON object.

Sometimes it’s possible to avoid any overlaps by creating per-service namespaces and keeping a list of “globally used” keys, along with definitions for them.

When developing software, it makes sense to have some internal document explaining which severity has which meaning. This avoids situations where failed login attempts to a publicly reachable service, or 404 error codes from crawlers requesting obsolete websites, raise an alarm and wake a colleague in the middle of the night. But even if that’s not the case, it can make debugging and being aware of problems a lot easier.

For this reason, it’s a good idea to clearly distinguish between the following:

  • Situations that might indicate a problem
  • Situations that should not happen, but can happen
  • Situations that clearly indicate a bug or more severe problem

Logs have the tendency to become more complex as software grows and services get added, so it’s a good investment to be clear about what to log and when from the very beginning.

In a corporate setting, it is typical to centralize logs. This makes it easier to connect the dots when debugging issues. It also means that in a distributed application, not every log on each physical or virtual machine or container has to be looked at individually. These centralized logging services typically make it easy and fast to query large amounts of logs, especially when the company uses structured logging and services adhere to a uniform log structure.

These logging services are either their own products, such as rsyslog, Loki, the ELK stack (Elastic Search, Logstash, and Kibana), and Graylog, or they are managed services. These can, for example, be the hosted variants of the services we just mentioned or cloud-specific logging solutions, such as Google’s operations suite (formerly known as Stackdriver), AWS CloudWatch, or Azure Monitor. There are many similarities between these systems in that they provide mechanisms to “ship” logs from files or via some kind of API, filter and restructure them, and eventually, save them into final storage, ready to be queried.

In microservice architectures, it’s common to pass along context, such as a request ID, so a request from a client can easily be traced through the various services, which is essential for debugging architectures that involve many services.

As mentioned, most of these systems have mechanisms to ship logs to the central log server or cluster. They go by names like Logstash (the L in ELK stack) and Promtail (used with Loki) and typically provide multiple ways of ingesting logs. For example, they might be configured to create an HTTP server, act as a syslog server, tap into journald, read from any other log shipping services, use cloud APIs, or simply tail files. They are run either as additional daemons on systems, as a Pod in Kubernetes, or as part of a Nomad setup. Since they are meant to allow centralizing logs no matter what software is in use, they tend to allow for a variety of log inputs and are typically very flexible on the setup side – for example, allowing one to create a hierarchy by forwarding between individual log-shipping services. On container orchestrators like Kubernetes and Nomad, this is often implemented with a “sidecar container” that runs next to your application containers and captures logs from all containers in that Pod/allocation/node before shipping them to their destination.

Figure 16.1: Container orchestration with a sidecar container

As you can see, while there are many technologies and products surrounding logging, they all fall into at least one of the categories described above, so when you centralize logging in your environment, this should give you an idea of how the parts relate to each other.

Logging can be a moving target in modern production environments. Learning and experimenting with the basics covered in this chapter should give you a good foundation. It is our hope that getting comfortable with syslog and journalctl will also equip you with a low-level understanding and historical perspective that will make it easier for you to work out how tomorrow’s logging-as-a-service solution actually works under the covers.

We think you’ll find that the skills you learned in this chapter give you a practical, measurable advantage when it comes to designing, debugging, and optimizing the applications you create and deploy. Mastering the basics of journald, as you just saw, lets you swiftly diagnose and pinpoint issues, whether they are related to your application specifically or to the larger Linux system around it. Having some understanding of alternative and historical Linux logging approaches will help when you’re troubleshooting systems (or people) that haven’t been updated in a long time.

It’s not just about solving issues; it’s also about making your life easier and your work better. Plus, it’s a skill that makes you stand out. In short, knowing your way around Linux logs makes you a smarter, more effective developer.