DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Autodiscovering Log Files for Logrotate

Mikko Ohtamaa user avatar by
Mikko Ohtamaa
·
Dec. 19, 12 · Interview
Like (0)
Save
Tweet
Share
2.72K Views

Join the DZone community and get the full member experience.

Join For Free

Logrotate is the UNIX application responsible for removing old (website) log file entries and preventing your server disk filling up. Logrotate is configured by writing config files where you specify one entry per file/file collection.

When you install applications like Apache or Nginx from your operating system package manager they usually come with a preconfigured logrotate entries. However, when you write your own custom software you need to take care of logrotation set up yourself.

If you are hosting a several website processes on the same server, e.g. Plone CMS sites, writing the log rotate entries for all log files manually can be pain. Below is a simple Python script which will auto discover all log files under a certain folder and its subfolders and generate logrotate entries for them.

The script is easy to adopt for other systems.

With Plone, since Plone uses buildout based installation process, you could alternatively use buildout configuration entries to maintain the log rotation for Plone. However, some sysadmins may prefer the system-wide logrotate configuration.

The script is hosted on Github for internal maintenance.

See also the related superuser.com question.

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""

    Auto-discover log files and generate logrorate config based on it.

    - Find any folders containing log files

    - Add logrotate entry for *.log files in that folder

    - Try to signal Zope application server after log rotation to release the file
      handle and actually release the disk space associated with it

    http://collective-docs.readthedocs.org/en/latest/hosting/zope.html#log-rotate

    http://man.cx/logrotate

    Usage example for Ubuntu / Debian::

        sudo -i -u  # root
        # Generate a log rotate config which is automatically
        # picked up by a log rotate on the next run
        discover-log-rotate /etc/logrotate.d/plone-all /srv/plone

    Confirm that it works by running logrotate manualy.

    Dry run, outputs a lot but doesn't touch the files::

        logrotate -f -d /etc/logrotate.conf

    Test run, rotates the files::

        logrotate -f /etc/logrotate.conf

    Also see that your processes can re-open log files after logrotate run
    by restating a sample process.

"""

__license__ = "Public domain"
__author__ = "Mikko Ohtamaa <http://opensourcehacker.com>"

import sys

import fnmatch
import os

#: Logroate config template applied for each folder.
#: Modify for your own needs.
TEMPLATE = """
%(folder)s/*.log {
        weekly
        missingok
        # How many days to keep logs
        # In our cases 3 months
        rotate 12
        compress
        delaycompress
        notifempty

        # THE FOLLOWING IS ZOPE SPECIFIC BEHAVIOR

        # This signal will tell Zope to reopen the file-system inode for the log file
        # so it doesn't keep reserving the old log file handle for even if the file is deleted
        # We guess some possible process and PID file names.
        # The process here is little wasfeful, but we don't need to try match a log file to a running process name.
        # TODO: Ideas how to get a process name from the log file name?
        postrotate
            [ ! -f %(installation)s/var/instance.pid ] || kill -USR2 `cat %(installation)s/var/instance.pid`
            [ ! -f %(installation)s/var/client1.pid ] || kill -USR2 `cat %(installation)s/var/client1.pid`
            [ ! -f %(installation)s/var/client2.pid ] || kill -USR2 `cat %(installation)s/var/client2.pid`
            [ ! -f %(installation)s/var/client3.pid ] || kill -USR2 `cat %(installation)s/var/client3.pid`
            [ ! -f %(installation)s/var/client4.pid ] || kill -USR2 `cat %(installation)s/var/client4.pid`
        endscript
}

"""

def run():
    """
    Execute the script.
    """
    if len(sys.argv) < 2:
        sys.exit("Usage: discover-log-rotate [generated config file] [directory]")

    config = sys.argv[1]
    folder = sys.argv[2]

    out = open(config, "wt")

    print "Running log rotate discovery on: %s" % folder

    # Find any folders containing log files
    matches = []
    for root, dirnames, filenames in os.walk(folder):
        for filename in fnmatch.filter(filenames, '*.log'):

            full = os.path.join(root, filename)
            dirpath = os.path.dirname(full)

            if not dirpath in matches:
                print "Adding log rotate entry for: %s" % dirpath
                matches.append(dirpath)

    for match in matches:

        folder = os.path.abspath(match)

        # Assume the main Zope installation folder is format /srv/plone/xxx
        # and the underlying log folder /srv/plone/xxx/var/log
        installation = os.path.abspath(os.path.join(folder, "../.."))
        cooked = TEMPLATE % dict(folder=match, installation=installation)
        out.write(cooked)

    out.close()

    print "Wrote %s" % config

if __name__ == "__main__":
    run()


operating system

Published at DZone with permission of Mikko Ohtamaa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Top 3 Challenges Facing Engineering Leaders Today—And How to Overcome Them
  • When AI Strengthens Good Old Chatbots: A Brief History of Conversational AI
  • Efficiently Computing Permissions at Scale: Our Engineering Approach
  • A Guide To Successful DevOps in Web3

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: