Custom Log Formats
LogFormat lets you define exactly which fields appear in each log line and in what order, including things the built-in formats don't capture at all, like response time or a specific request header.In this page:
The LogFormat Directive
LogFormat "format-string" nickname defines a named format built from percent-escape codes, which CustomLog then references by that nickname. Apache ships two built-in ones: common (a minimal older format) and combined (adds the referrer and user agent), both already defined for you in the default config.
Common Format Codes
%h is the client's IP address, %t the timestamp, %r the first line of the request, %>s the final HTTP status code, %b the response size in bytes, %{Referer}i and %{User-Agent}i pull specific request headers by name, and %D gives the time taken to serve the request in microseconds.
Why Build a Custom Format
The built-in combined format doesn't include response time at all -- adding %D is one of the most common customizations, since it lets you find slow requests directly from the log instead of needing separate application-level profiling. Logging a specific header, like an API key or a request ID passed through from a load balancer, is another common reason to define your own format.
Format for Machine Parsing
If logs feed into a system like the ELK stack, Splunk, or a custom parser, a structured format -- even something like JSON built entirely out of LogFormat's codes -- is often easier to ingest reliably than parsing the space-and-quote-delimited default format with regular expressions.
%D (response time) to your access log format early -- it costs nothing to log and is often the single most useful field for spotting a slow endpoint before users complain about it.Example: A custom format that includes response time
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %D" timed
CustomLog /var/log/apache2/example.com-access.log timed
{# Flagged by hand after confirming a runner can't handle this example
(a shell command / go.mod file stored as a TopicExample, a language
feature the configured runner version doesn't support, or output
that blows a runner's sandbox limit) -- see TopicExample.norun.
Never render the run button for these, regardless of language,
since it would just fail at execute_code (or worse, hang the
Judge0 queue on a submission that can never finish cleanly). #}
- Defining a LogFormat but forgetting to reference its nickname in CustomLog, so the site keeps using whatever format was already active.
- Redefining a built-in nickname like
combinedwith different fields, which silently changes the format for every CustomLog directive elsewhere that assumes the original meaning. - Choosing a hand-rolled delimited format when a structured one (e.g. JSON) would parse far more reliably in whatever tool actually reads the logs downstream.
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: