Skip to content

Logging

Brad Mostert edited this page Oct 1, 2016 · 10 revisions

A Monolog logger is configured for each command that extends the BaseCommand class. It can be accessed by calling $this->getLogger(), which returns an object that implements the PSR-3 LoggerInterface. You can use this in the same way that you would use the logger returned by Symfony's built in logging service. This logger is pre-configured with handlers to log to your terminal and to file.

As with everything else in the bundle, this is fully customizable.

Table of Contents

Why is this Useful?

For small projects, you could probably get away with just using Symfony's built in logging service, however as your project grows, having independently configurable loggers may become useful for the following reasons:

  • Different commands may require different levels of logging verbosity depending on their maturity
  • You will probably want different commands to log to different places for both IO performance and easy of readability
  • A useful paradigm is to only use Symfony's logging service for log entries related to web requests in order to differentiate these

Example Usage

In the following example, log entries are written to record the beginning and end of the command's execution. These are logged at the INFO level of verbosity while the contents of any exceptions are logged at the ERROR level of verbosity. In the initialize() function the global default logging level of WARNING is overridden for this command so that that INFO log entries are outputted.

use Monolog\Logger;

// ...

protected function initialize(InputInterface $input, OutputInterface $output)
{
    $this->setLogLevel(Logger::INFO); // Override default of WARNING
    parent::initialize($input, $output);
}

protected function execute(InputInterface $input, OutputInterface $output)
{
    $this->getLogger()->info('Starting Execution');

    try {
        // Do so stuff
    } catch(\Exception $e){
        $this->getLogger()->error('Exception Encountered: '.$e->getMessage());
    }

    $this->getLogger()->info('Done');
}

The idea is that once this code becomes stable, the setLogLevel() line can be removed so that only the exception messages are logged. The entries that are logged at INFO verbosity can be left in the code so that if the extra verbosity is ever needed again to debug, the entries can be accessed (per execution) using the --log-level parameter.

This is a simple example. There is a large variety of other logging functionality detailed in the Function Reference.

Global Config

All the configuration options for the Logging Enhancement fall under the logger config node. As all fields have 'sensible' defaults, no configuration is required to start using the bundle. These options are available should you want to customise the logging functionality to your needs. The default values are shown below:

afrihost_base_command:
    logger:
        handler_strategies:
            file_stream:
                enabled:              true
                line_format:          '%%datetime%% [%%level_name%%]: %%message%%'
                file_extension:       .log.txt
                allow_line_breaks:    false   
            console_stream:
                enabled:              true
                line_format:          '%%datetime%% [%%level_name%%]: %%message%%'
                allow_line_breaks:    true

Handler Strategies

There are currently two Monolog LogHandlers that are automatically configured by default:

  1. File Stream
  2. Console Stream

Both handlers will log at WARNING verbosity by default. This can be overridden per command using the setLogLevel function or at runtime using the --log-level parameter.

File Stream

This handler will output log records to a log file. The file will be created in the default Log Directory of the executing Symfony Kernel. Typically this is app/logs/.

Unless explicitly specified in the implementation of the command, the default filename will be the same as the name of the PHP file in which the command class is implemented with .log.txt appended as an extension.

For example: if you have a command defined in HelloWorldCommand.php the log file will be called HelloWorldCommand.php.log.txt (see the setLogFilename and setDefaultLogFilenameExtension function references for more information)

Enabled

Logging to file can be enabled or disabled by setting this field to true or false respectively. The default is true. This can be overridden on a per command basis using the setLogToFile function.

Line Format

Provide the string format that the LineFormatter will be configured with by default when logging to file. You can also specify null to use the Monolog default of [%datetime%] %channel%.%level_name%: %message% %context% %extra%'. . A new line character will automatically be appended to the line format when logging to file. The Line Format can also be changed per command using the setFileLogLineFormat function.

File Extension

The extension of the automatically generated log file name. This is not used when a specific log file name is provided using the setLogFilename function.

Allow Line Breaks

Configure if newline characters in log records should be outputted when logging to file by default. Stripping new lines is useful for logs parsed by machines as it means that one line corresponds to one log entry.

Console Stream

This handler will send a copy of your log records to your terminal. This helps avoid duplication of your output code as it allows everything that is being written to file to also be read directly from terminal when manually executing a command. The functionality is achieved via the Symfony OutputInterface used by the command and thus it is compatible with other symfony tools (such as the CommandTester)

Enabled

Logging to console can be enabled or disabled by setting this field to true or false respectively. The default is true. This can be overridden on a per command basis using the setLogToConsole function.

Line Format

Provide the string format that the LineFormatter will be configured with by default when logging to console. You can also specify null to use the Monolog default which is [%datetime%] %channel%.%level_name%: %message% %context% %extra%'. . A new line character will automatically be appended to the line format when logging to console. The Line Format can also be changed per command using the setConsoleLogLineFormat function.

Allow Line Breaks

Configure if newline characters in log records should be outputted when logging to console by default. Allowing new lines is useful for logs that are read by humans as it improves readability.

Parameters

Sometimes you have a need to change the logging configuration for a single execution of a command. In the case of logging, this is most common when trying to debug a failure that results from a particular situation. There is thus a parameter to change the log level for a single execution to assist with this.

--log-level

The logging verbosity of a single execution can be changed by providing this parameter. It takes a string value that must correspond to one of Monolog's string names for the RFC 5424 log levels. For reference these are:

  • DEBUG
  • INFO
  • NOTICE
  • WARNING
  • ERROR
  • CRITICAL
  • ALERT
  • EMERGENCY

A log record that reads LOG LEVEL CHANGED: <level> is added to explain the change in verbosity. This is useful for when the logs are reviewed at a later stage.

There is a shortcut for this parameter for historical reasons. The shortcut is: -l

Here is an example of changing the log level to NOTICE for a single execution

$ php app/console my:super:command --log-level=NOTICE 

What Next

Learn more about customising logging functionality per command with the Logging Function Reference