Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk9 min

How to Configure Logging and Log Rotation in Apache on Ubuntu

Set per-site Apache access and error files on Ubuntu, build a safe logrotate policy, verify post-rotation writes, troubleshoot stale file handles, and understand when piped rotatelogs is appropriate.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

On Ubuntu, Apache writes request records to /var/log/apache2/access.log and server diagnostics to /var/log/apache2/error.log unless a virtual host overrides those destinations. Use CustomLog for requests and ErrorLog for errors, then let logrotate rename, compress and retain old files. A reload in logrotate’s postrotate block is essential: without it, Apache can continue writing to the renamed file through its existing open file handle.

This guide shows a complete per-site setup, a safe rotation policy, validation and recovery steps, and when Apache’s piped rotatelogs is a better fit.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Know what Apache is logging and where

Ubuntu’s packaged Apache configuration uses two main destinations:

Purpose Default Ubuntu path Directive that overrides it
HTTP requests, status codes, bytes and other transfer fields /var/log/apache2/access.log CustomLog
Startup messages, warnings, module errors and request-processing errors /var/log/apache2/error.log ErrorLog

The defaults apply when a virtual host does not define its own destinations. A site-specific directive is useful when several domains share a server: each site can have separate files for incident investigation, traffic analysis and retention.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

CustomLog controls request records

The directive takes a destination followed by a log format. The common Ubuntu example uses the built-in combined format:

CustomLog ${APACHE_LOG_DIR}/example_access.log combined

${APACHE_LOG_DIR} expands to Ubuntu’s Apache log directory, normally /var/log/apache2. The format determines which request fields are written; combined is the conventional choice when you need standard client, request, referrer and user-agent information.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

ErrorLog controls server diagnostics

An error destination has no format argument:

ErrorLog ${APACHE_LOG_DIR}/example_error.log

Apache writes diagnostic messages there according to its configured log level. Keep access and error records separate so a burst of requests does not hide startup or application-proxy failures.

Piped logging is a different mode

If the value begins with a vertical bar (|), Apache starts a logging program and sends records to it instead of opening an ordinary file itself. This is how the rotatelogs alternative works. Piped logging changes the process, permissions and failure considerations, so do not add the bar to a normal filename.

Assign separate files to an Ubuntu virtual host

1. Edit the site definition

Virtual-host files live in /etc/apache2/sites-available/. Edit the file for the domain, or create one such as example.conf:

<VirtualHost *:80>
    ServerName example.com
    CustomLog ${APACHE_LOG_DIR}/example_access.log combined
    ErrorLog  ${APACHE_LOG_DIR}/example_error.log
</VirtualHost>

Place the directives inside the relevant <VirtualHost> block. The two paths may be changed to another directory, but that directory must exist and have permissions that allow Apache to open the files. Keeping them under ${APACHE_LOG_DIR} makes Ubuntu’s standard log policies and administration tools easier to apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

2. Enable the site when necessary

If this is a new or disabled site, enable it with:

sudo a2ensite example.conf

If the file was already enabled, this command is harmlessly redundant; the important point is that Apache must load the file from sites-enabled.

3. Validate before touching the running service

Run Apache’s configuration test:

sudo apache2ctl configtest

Proceed only when the result is Syntax OK. A misspelled directive, an invalid path or a malformed virtual-host block can otherwise make a reload fail.

4. Reload, do not stop, Apache

Apply the valid configuration without interrupting existing connections:

sudo systemctl reload apache2

A reload also causes Apache to reopen log files. This matters after logrotate renames the active file, as described below.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

5. Watch both files while generating a request

Use two terminals, or follow both paths in one command:

sudo tail -f /var/log/apache2/example_access.log /var/log/apache2/example_error.log

Request http://example.com/ in a browser or with a suitable HTTP client. A successful request should add a line to the access file. Configuration or upstream failures should appear in the error file; an empty error file is normal when no error has occurred.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Choose a rotation policy that matches the service

Ubuntu’s normal external mechanism is logrotate. Its policies are read from files under /etc/logrotate.d/ in addition to the main configuration. A policy can rotate on a calendar interval or a size threshold, compress old files, retain a chosen number, and run commands after the rename.

Frequency and retention are operational decisions

  • Daily: useful for busy sites where a day’s records would become large or difficult to search.
  • Weekly or monthly: reduces the number of archive files on low-traffic systems.
  • Size-based: appropriate when traffic is bursty and file size matters more than a calendar boundary.
  • Retention count: balance disk capacity, incident-response needs and any legal or contractual retention requirement. The example below keeps 14 rotations; that is not a universal recommendation.

Compression saves space but adds decompression work when investigating old events. delaycompress leaves the newest rotated file uncompressed for one cycle, which can be convenient when another process still needs immediate access.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create or adjust the Apache policy

Place a policy in a file under /etc/logrotate.d/, using a name that does not create a duplicate rule for the same files. Ubuntu installations often include an Apache policy already; inspect existing files before adding another glob so one log is not rotated twice.

/var/log/apache2/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    sharedscripts
    postrotate
        systemctl reload apache2 > /dev/null 2>&1 || true
    endscript
}

What each directive does

Directive Effect Reason to keep or change it
daily Checks the files every day for rotation. Change to weekly, monthly or a size rule when that better matches traffic.
missingok Does not report an error when a matching file is absent. Useful when a virtual host has not produced a log yet or a site is temporarily disabled.
rotate 14 Keeps 14 older rotations before removing the oldest. Set this from storage and retention requirements, not by copying the example blindly.
compress Compresses older rotated files. Reduces disk use; tools must read compressed archives when investigating history.
delaycompress Defers compression of the most recent rotated file until the next cycle. Can help processes that briefly need the newest archive as an ordinary file.
notifempty Skips rotation for an empty log. Avoids creating meaningless archives for quiet sites.
sharedscripts Runs the script once for the whole matched set rather than once per file. Prevents multiple Apache reloads when access and error files rotate together.
postrotate … endscript Runs the enclosed command after renaming the files. The reload tells Apache to open the new active paths.

If you use a custom directory or add a create directive, verify the resulting owner, group and mode. A newly created file that Apache cannot write will stop fresh records even though the service itself remains running.

Test logrotate without losing data

Preview the policy

Use debug mode to parse the complete configuration and show what would happen:

sudo logrotate --debug /etc/logrotate.conf

The manpage specifies that --debug makes no changes. It is the safest first check for a path glob, syntax error or unexpected duplicate policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Force one intentional rotation

To exercise the rename, compression and reload path immediately:

sudo logrotate --force /etc/logrotate.conf

--force rotates even when logrotate’s state says the files are not yet due. Use it deliberately on a production host because it creates archives and triggers the postrotate action.

Verify the active file after rotation

  1. Force or wait for a real rotation.
  2. Generate a fresh request:
curl -I http://example.com/
  1. Inspect names, timestamps and sizes:
sudo ls -lh /var/log/apache2/
  1. Confirm that the new active file contains the request:
sudo tail -n 5 /var/log/apache2/example_access.log

The active file should continue growing, while the renamed archive should stop changing. Compressed archives normally have a compression suffix after the applicable delay.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why the postrotate reload is mandatory

Renaming a pathname does not automatically change a process’s open file descriptor. Apache can continue writing to the old inode after logrotate has moved it to an archive name. The apparent symptom is that the new example_access.log stays empty while the rotated file keeps increasing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Apache’s logging guidance explicitly requires a reload (or an equivalent signal) in logrotate’s postrotate script. The example uses:

systemctl reload apache2 > /dev/null 2>&1 || true

The redirection keeps routine output out of cron notifications. || true prevents a transient reload error from making the entire rotation job report failure; it should not be used as a substitute for monitoring. If reloads are failing, run the command manually and inspect the service status and journal.

Diagnose a file that keeps receiving new lines

  1. List the directory and compare the modification times of the active and rotated files.
  2. Check that the policy actually matches the path used by the virtual host. A site writing to /var/log/apache2/example_access.log is not covered by a policy that names only another directory.
  3. Run sudo systemctl reload apache2 manually.
  4. Send a new request and watch the intended active file with tail -f.
  5. If the old file still grows, inspect for another Apache process, a second virtual-host directive, or a piped logger. Do not delete the growing archive until you have identified its writer.

Use rotatelogs when Apache should own the rotation stream

Apache also supplies rotatelogs, which receives piped log records and creates new files after an elapsed interval or size threshold. Ubuntu documentation shows time-based rotation at 86,400 seconds (one day), local-midnight naming, and a 5-megabyte threshold.

Time-based example

CustomLog "|/usr/bin/rotatelogs /var/log/apache2/example_access.log 86400" combined

The leading pipe makes this a program command. The 86,400-second value requests daily elapsed-time rotation; the resulting filenames include the time information supplied by rotatelogs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Size-based error logging example

ErrorLog  "|/usr/bin/rotatelogs /var/log/apache2/example_error.log 5M"

Here the threshold is 5 megabytes. Apply the same care to the command path and directory permissions as with ordinary files.

Decide between the two approaches

Requirement logrotate with ordinary files Piped rotatelogs
Rotation trigger Calendar or policy-based size checks. Elapsed time or file-size threshold handled by the logger.
Compression and retention Provides standard compression, delayed compression and retention counts. Not supplied by the basic command examples; arrange separate archival management if required.
Service integration Fits Ubuntu’s shared logrotate administration and uses a postrotate reload. Apache manages a logging pipe continuously.
Best fit Hosts that standardize permissions, retention and compression across services. Deployments that specifically want Apache-managed time or size thresholds.

This is an operational choice, not a requirement to use both. Do not put the same logical stream through an ordinary-file logrotate rule and a piped logger at the same time.

Security, privacy and permissions

Protect the log directory

Write access to an Apache log directory is security-sensitive. Restrict directory ownership and mode to the service account and authorized administrators. A user who can replace or alter a log destination may influence what Apache executes or erase evidence, depending on the surrounding configuration.

Avoid collecting secrets by default

Access logs can contain URLs, query strings, referrers and user-agent data. Do not deliberately log passwords, authorization headers, session tokens or unnecessary personal data. If a reviewed requirement demands sensitive fields, define who may read them, how long they are retained and how archives are protected.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check every new archive

After the first rotation, inspect both active and archived files. Confirm that Apache can append to the active file, that archive permissions do not expose data to unrelated users, and that compression did not move files outside the expected directory. Custom create settings deserve particular attention because they determine the mode and ownership of newly created logs.

Troubleshooting by symptom

No access lines appear after changing the virtual host

  • Run sudo apache2ctl configtest and correct any syntax error.
  • Confirm the site is enabled with a2ensite and that the request reaches the expected ServerName.
  • Reload Apache after the edit.
  • Check that the directory exists and is writable by Apache.
  • Verify that the request is using the exact filename configured in CustomLog.

The error file is empty

An empty error file does not indicate failure; it may simply mean no server error has occurred. Generate a harmless request and inspect Apache’s service status if you suspect a startup problem. Do not move diagnostics into the access file merely to make the error file nonempty.

Rotation runs but the active file is not updated

Check the postrotate reload first. Then verify that the policy’s glob includes every custom filename. If Apache uses a pipe, ordinary file rotation will not control that stream; inspect the rotatelogs command instead.

Disk usage keeps rising

  • Check whether compression is enabled and whether delaycompress is behaving as expected.
  • Review the number of retained rotations and the actual traffic volume.
  • Look for logs outside /var/log/apache2, including custom directories.
  • Inspect for a process still writing to an old renamed file.

Operational checklist

  • Define CustomLog and ErrorLog inside the correct virtual host.
  • Use paths covered by exactly one intended rotation policy.
  • Run sudo apache2ctl configtest before every reload.
  • Apply changes with sudo systemctl reload apache2.
  • Use logrotate --debug to preview policy behavior.
  • Include an Apache reload in postrotate after external renames.
  • Force a test rotation only when you are prepared for archive creation.
  • Send a fresh request and verify that the new active file grows.
  • Review archive ownership, modes, compression and retention against operational and legal requirements.
  • Keep secrets and unnecessary personal data out of logs.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.