phpstatic-methodslog4php

What is the best way to add logging to static methods in utility classes?


I am trying to figure out the best way to add logging to my static methods in utility classes. I am using log4php for logging. What I would like to do is:

<?php
require_once  WEBSITE_BASE_DIR . "/log4php/Logger.php";

class TestUtil
{
    private static $log = Logger::getLogger( "testutil" );

    public static function utilMethod1()
    {
        self::$log->trace("Entering utilMethod1");

        // ... do stuff ...

        self::$log->trace("Exiting utilMethod1");
    }

    public static function utilMethod2()
    {
        self::$log->trace("Entering utilMethod2");

        // ... do stuff ...

        self::$log->trace("Exiting utilMethod2");
    }
}

However, I can't do this in PHP and get a syntax error on the initialization of the $log static variable. The only way that I can figure out how to do this is to add an init() call to every static method:

<?php
require_once  WEBSITE_BASE_DIR . "/log4php/Logger.php";

class TestUtil
{
    private static $log = NULL;

    private static function init()
    {
        if (self::$log == NULL)
        {
            self::$log = Logger::getLogger( "testutil" );
        }
    }

    public static function utilMethod1()
    {
        self::init();
        self::$log->trace("Entering utilMethod1");

        // ... do stuff ...

        self::$log->trace("Exiting utilMethod1");
    }

    public static function utilMethod2()
    {
        self::init();
        self::$log->trace("Entering utilMethod2");

        // ... do stuff ...

        self::$log->trace("Exiting utilMethod2");
    }
}

But this seems like an excessive amount of redundant code, giving that I have many utility classes with many static methods. Is there a better way to do this?


Solution

  • You could have a static method that defines the logger. You can call this once when you are starting your application.

    public static function setLogger(LogInterface $logger)
    {
        self::$log = $logger;
    }
    

    A second thing you could do is have a static method that returns the logger instance instead of using a static property.

    private static function log()
    {
        return Logger::getLogger( "testutil" );
    }
    

    Then instead of calling self::$log->trace(), you would just call self::log()->trace().