Undefined error log

Hello! I'm having an issue with logging variables if I expect them to sometimes be null or undefined. I am using a custom formatter, but disabling this does not fix the problem. Error when cons...

Updating winston to 3.0.0-rc5 does in fact fix the error, or rather: make another error in my own code apparent. Updating just made the error go silent, because errors happening within my formatter code was not printed (see below).

So there was en error with rc1, but it’s fixed now, thanks!

This is also made apparent by the fact that format.json() is now working with logger.debug(null);.

(Sorry @indexzero, didn’t find that issue before posting!)

My error

In case anyone else comes across the same error. Rookie mistake, I know, but see «Something odd» below for why I didn’t catch this.

The error I had in my code was calling:

Object.keys(info.message);

when info.message could be null without null-checking it.

Something odd

This however, did not log any errors, which is odd, and made the mistake hard to spot and fix. My code is definitively wrong, but shouldn’t this log an error, at least to the console? This might also be something to do with how Object.keys() is impl., and not winston.

Specifically, when calling logger.debug(null); this code produces no errors and stops execution:

const myFormat = format.printf((info) => {
    console.log(info.message);
    let t = Object.keys(info.message);
    return info.message;
}

And outputs to console:

While this code produces an error (as one would expect) and stops execution:

const myFormat = format.printf((info) => {
    console.log(info.message);
    let t = Object.keys(null);
    return info.message;
}

With this output to console:

D:GitPrivateDdSG_Serverlogger.js:8
   let t = Object.keys(null);
                  ^

TypeError: Cannot convert undefined or null to object
   at Function.keys (<anonymous>)
   at Printf.format.printf [as template] (<...>logger.js:8:20)
   at Printf.transform (<...>node_moduleslogformprintf.js:15:26)
   at Format.cascaded [as transform] (<...>node_moduleslogformcombine.js:34:24)
   at DerivedLogger._transform (<...>node_moduleswinstonlibwinstonlogger.js:229:25)
   at DerivedLogger.Transform._read (_stream_transform.js:186:10)
   at DerivedLogger.Transform._write (_stream_transform.js:174:12)
   at doWrite (_stream_writable.js:387:12)
   at writeOrBuffer (_stream_writable.js:373:5)
   at DerivedLogger.Writable.write (_stream_writable.js:290:11)

Setup

For completeness, here’s my logger setup (logger.js.):

const winston = require('winston');

const format = winston.format;

const myFormat = format.printf((info) => {
    const timestamp = (new Date()).toLocaleTimeString();

    let parsedMessage;
    if (/*info.message && <ADDED NOW>*/typeof info.message !== 'string' && Object.keys(info.message).length > 1) {
        parsedMessage = `n${JSON.stringify({ ...info.message }, null, 2)}`;
    } else if (typeof info.message !== 'string') {
        parsedMessage = `${JSON.stringify(info.message)}`;
    } else {
        parsedMessage = info.message;
    }

    let logMessage = `${timestamp} ${info.level}: ${parsedMessage}`;

    return logMessage;
});

const logger = winston.createLogger({
    level: 'info',
    format: format.combine(format.colorize(), myFormat),
    transports: [
        new winston.transports.Console({
            level: 'silly'
        }),
        new winston.transports.File({
            filename: 'error.log',
            level: 'error'
        }),
        new winston.transports.File({
            filename: 'combined.log'
        })
    ]
});

global.logger = logger;

 on
May 06, 2021

The Essential Guide to PHP Error Logging

PHP has been one of the top (if not best) server-side scripting languages in the world for decades. However, let’s be honest – error logging in PHP is not the most straightforward or intuitive. It involves tweaking a few configuration options plus some playing around to get used to. Once you have everything set up and figured out (like you will after reading this post), things seem much easier, and you realize how helpful error logging can turn out to be for your application – from debugging and troubleshooting to monitoring and maintenance. 

And this is why we are covering error logging in PHP in this post. We will start by revisiting the importance of logging errors in your application. We will then explore errors in PHP – their different types, and how they can be output. Next, we will look at all the error logging configurations in PHP, and understand how we can tweak these to our liking, before we see some error logging examples, and explore functions in PHP that allow us to write errors to log files. This post is a complete guide to error logging in PHP.

Here’s an outline of what we’ll be covering so you can easily navigate or skip ahead in the guide: 

  • Importance of Logging Errors 
  • PHP Error Types
  • Where Can PHP Errors be Output
  • Enabling and Configuring Error Reporting in PHP 
  • Logging Errors in PHP 
  • PHP’s Error Logging Functions 
    • error_log()
    • trigger_error()
    • syslog()
    • set_error_handler()
  • Popular PHP Logging Libraries 

Importance of Logging Errors 

Errors in software systems have this terrible reputation of being associated with failing things and breaking functionality. As a result, many of us often fail to recognize the importance of these loud red strings that bring our attention to faults, inconsistencies, and inaccuracies in our code – mistakes that can cost us dearly if allowed to fall through the cracks. Therefore, it is worthwhile for some of us to change our outlook towards error messages – to track, log, and organize them – and embrace their importance. 

There’s a reason developers and organizations build and leverage dedicated logging systems that keep track of errors that arise throughout an application’s lifecycle. These logs provide useful information about what went wrong, when, where, and how it can be fixed. 

For small-scale personal projects, it is common for developers not to feel the need to spend time setting up an effective logging system. This seems plausible because your code and end-user interactions are much more manageable for smaller projects. However, the requirement for effectively logging and maintaining errors and other information grows exponentially as your application scales. For larger applications, catering to thousands of users, it becomes unwieldy to track errors and updates across hundreds of components in real-time. Putting in place a system that can record the status of the very many events that an application’s operation entails allows organizations to maintain a clear record of their performance. This allows for more transparency and therefore ensures that no issues go unnoticed. As a result, this makes your application more reliable, easy to maintain, monitor, and debug.

Now that we are hopefully convinced that error logging is a worthwhile expedition, let us look at the different types of errors in PHP.

PHP Error Types

Broadly, there are five types of errors in PHP:

1. Fatal run-time Errors (E_ERROR) 

These errors typically happen when an operation in your code cannot be performed. This leads to your code exiting. An example of a fatal error would be when you call a function that hasn’t been defined in your code, shown below:

<?php
function foo() {
  echo "Function foo called.";
}
boo(); // undefined function 'boo'
?>

Error output –>

Fatal error: Uncaught Error: Call to undefined function boo() in code/my-php/index.php:5 Stack trace: #0 {main} thrown in code/my-php/index.php on line 5.

2. Warning Errors (E_WARNING)

A warning error is more gentle and less obtrusive in that it does not halt the execution. It presents a friendly reminder of something amiss in your code – a mistake that might not fail things immediately or fail anything at all but suggests a more accurate way of doing things that make your code more foolproof. These warnings can also save developers from issues that might pose a much bigger threat in the future. An example of a warning error would be when you try to include a file in PHP using an incorrect file path, as shown below:

<?php
include('filename.txt'); // arbitrary file that is not present
echo "Hello world";
?>

Error output ->

Warning: include(filename.txt): failed to open stream: No such file or directory in code/my-php/index.php on line 2

3. Parse Errors (E_PARSE)

Parse errors are also known as syntax errors as they arise from syntactical mistakes in your code. These errors are raised during the compilation of your code, making it exit before it runs. A common example of a parse error is missing a semicolon at the end of a code statement, shown below:

<?php
echo Hello world // no quotes or semicolon used
?>

Error output ->

Parse error: syntax error, unexpected 'world' (T_STRING), expecting ',' or ';' in code/my-php/index.php on line 2.

4. Notice Errors (E_NOTICE)

Notice errors are minor errors that are encountered during run-time, and just like warning errors, do not halt the execution. They usually occur when the script is attempting to access an undefined variable, for example, as shown below:

<?php
$a = 1;
$c = $a + $b; // undefined variable $b
?>

Error output ->

Notice: Undefined variable: b in code/my-php/index.php on line 3

5. User Errors (E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE) 

User errors are user-defined, i.e., present a custom user-generated message raised explicitly from the code to capture a specific condition. These errors are manually raised by developers using the trigger_error function instead of the PHP engine. They are further classified as fatal, warning, and notice errors, but we’ll group them all as user errors for simplicity.

Where can PHP Errors be Output?

There are two primary places where we can have our errors presented in PHP – through inline errors and dedicated error log files.

Inline Errors 

Inline errors are those that show up on your webpage in the browser or your terminal via STDOUT in a command-line environment. These errors prove to be quite useful during development – for developers to debug their code, fix issues, and get information about the overall execution. Below is an example of what these errors usually look like in the browser:

undefined

Though this proves to be super helpful for developers, you should be very careful in ensuring that these errors are not output when your application goes into production – for two reasons – end-user experience and security. You can toggle the displaying of these errors using the display_error directive in your system’s configuration. We’ll dive deeper into this in the next section.

Error Log Files 

Inline errors are not persistent in memory, i.e., they are not saved anywhere and are only viewed as long as the browser or terminal session is alive. Additionally, you’ll only want to have them in a development environment. Conversely, as the theme of this post suggests, logging your errors is the more intelligent and more systematic approach towards maintaining large-scale applications. These are persistent in memory and provide information about the operation of your application across multiple components in one place, making it easier for monitoring and troubleshooting.

PHP, therefore, allows you to direct all your errors to specific log files; these files store timestamps, error stack traces, custom messages, and other helpful information about the source of the error and how to fix it. You can specify the path of your custom log file using the error_log directive of your system configuration. Here’s an example of an error log file:

undefined

You can also choose to have your errors logged to the system’s log file, usually located in – /var/log/syslog. We’ll cover this in a later section in the post.

Now let’s look at how we can configure where and how we want our errors logged.

Enabling and Configuring Error Reporting in PHP 

As we discussed previously, logging in PHP is slightly less straightforward than other languages and frameworks. You might have to tweak a few options in configuration files to customize logging patterns. For example, when you install PHP on your machine, the initial configuration comes with some aspects of error logging disabled. This differs from system to system, and therefore, you should manually check these settings before getting started.

Logging Configuration Options in php.ini File

The configuration options are in the php.ini file. This file is read when PHP starts up and allows developers to play around with PHP’s functionality. Usually, this file can be found somewhere in the /etc/php directory on most Linux systems. 

There are a bunch of directives (options) pertaining to the logging of errors in PHP that we can configure in this php.ini file:

  • display_errors (default: 1)

Display errors are the inline errors we previously looked at. This directive can be used to good effect during development to output PHP error messages to the browser or terminal. However, for applications in production, you should likely turn this off to save your users from a poor website experience due to obscure error messages. Not only that, but this also protects you from exposing valuable information about the internals of your application as a security measure.

  • display_startup_errors (default: 0)

As the name suggests, this is to output any errors that take place when PHP starts up. These usually do not provide any valuable information about your application specifically, and therefore need not be turned on.

  • log_errors (default: 0)

This directive allows you to toggle the logging of errors to the specified path (in the next directive). Because this is turned off by default, it would be advisable to toggle this to 1 for recording your application’s error messages in a log file.

  • error_log (default: 0)

This directive allows you to specify the path of your log file. You can also set this to “syslog” for directing all your error log messages to the system log. 

  • error_reporting (default: null)

The error_reporting directive allows you to customize which error levels you want reported, and which you are okay with going unreported. For example, you can use the directive as shown below to have all errors reported: error_reporting = E_ALL

  • track_errors (default: 0)

This directive allows you to access the last raised error message in the $php_errormsg global variable in your code and can keep track of errors across your whole project.

After making changes to your php.ini file, you will need to restart the server for the changes to take effect.

The ini_set() Function

However, if you are unable to locate the php.ini file, or prefer overriding your project’s global configuration options, there is also an option to update these directives using the ini_set() function in your PHP code. For example, the below code can be used for customizing error reporting in your project:

<?php

// enabling error logging
ini_set('log_errors', 1);  

// Customize reporting of errors
ini_set('error_reporting', E_WARNING | E_ERROR | E_PARSE | E_NOTICE);

// specify error log file path
ini_set('error_log', '/tmp/my-logs.log');

?>

The error_reporting() Function

One can also modify the error_reporting configuration option using the error_reporting() function from inside your code during run-time. As in the ini_set function, you can use bitwise operators like OR (|), AND (&), NOT (~), etc., when specifying the error levels to be reported. Below are a few examples of how this function can be used.

// Report only selected kinds of errors
error_reporting(E_ERROR | E_PARSE | E_NOTICE);

or

// Report all errors except E_WARNING
error_reporting(E_ALL & ~E_WARNING);

Now that we have got the system configurations and overall setup out of the way, let’s look at an example of how errors in your project code can be logged to files on your system.

Logging Errors in PHP

First, we will override the logging configuration parameters using the ini_set() function to enable error logging and specify the log file’s path. Then we’ll write some erroneous code to have PHP raise an error that we would like to have logged.

<?php
  ini_set('log_errors', 1); // enabling error logging
  ini_set('error_log', '/path/my-error-file.log'); // specifying log file path

  echo $b; // undefined variable should raise error
?>

After opening the web page on our browser, let’s open the ‘my-error-file.log’ file to see if the error message was logged. Here is the log file output:

[28-Feb-2021 13:34:36 UTC] PHP Notice:  Undefined variable: b in code/my-php/index.php on line 5

As you can see, our notice error was logged with a timestamp. As our code encounters more and more errors, this file will keep getting populated with corresponding timestamps. Note that we haven’t explicitly turned off display_errors, so these error messages are likely to be logged to the browser web page – something you might want to avoid during production. 

This was an example of capturing errors raised by PHP in log files. Now let’s look at how we can raise and log custom error messages for our application.

PHP’s Error Logging Functions

So far, we looked at errors raised by PHP – errors about your code execution. However, oftentimes you would want to also capture custom errors, with custom error messages specific to the functioning of your application. These so-called errors might not necessarily fail your code or halt its execution, but can indicate conditions characterized as erroneous and noteworthy for your application. These can act as indications to the organization about anomalous behavior that the team might want to look into and fix.

To facilitate this, PHP provides a set of functions that we can use to actively log errors in our code.

error_log()

The most common method for actively logging errors is the error_log() function. This sends a string argument for the error message to the log file.

error_log (string $message, int $message_type=0, string $destination=?, string $extra_headers=?) : bool

It also takes many other parameters to send error messages over email or specific log files. However, for the sake of simplicity, we won’t be covering that here. 

The interesting thing about this function is it logs your error message to the file specified in the configuration (or to the system log), regardless of the value of the log_errors directive. Let’s take a very simple example of logging an error when a specific condition in our code is met.

<?php

ini_set('error_log', '/path/my-error-file.log');
$a = 5;
$b = 10;

$c = $a + $b;

if ($c < 20) {
error_log("Sum is less than 20."); // logging custom error message
}

?>

Here is the output of the log file:

[28-Feb-2021 13:31:50 UTC] Sum is less than 20

Similarly, you can also log the values of variables in your code to provide additional context about your errors. Let’s see an example for that:

<?php
  ini_set('error_log', '/path/my-error-file.log');

  $languagesArray = array("PHP", "Python", "Node.js");
  error_log("Lorem ipsum. Array data -> ".print_r($languagesArray, true));
?>

Here’s the output of the log file ->

[28-Feb-2021 13:49:28 UTC] Lorem ipsum. Array data -> Array

(

   [0] => PHP

   [1] => Python

   [2] => Node.js

)

trigger_error()

The trigger_error() function can be used to raise a user-defined error/warning/notice. You can also specify the error type based on the condition. This allows you to customize its reporting and other behavior – for example, using an error type of E_USER_ERROR. We can cause the code to exit immediately compared to an E_USER_WARNING error.

trigger_error (string $error_msg, int $error_type=E_USER_NOTICE) : bool

The difference between trigger_error and error_log is that the former only generates a user error and depends on your system’s logging configurations to handle this error message (whether displayed or logged). error_log, on the other hand, will log your message regardless of the system’s configuration.

Here is the code for the same example we saw previously:

<?php
ini_set('log_errors', 1); // enabling error logging
ini_set('error_log', '/path/my-error-file.log'); // specifying log file path

$a = 5;
$b = 10;
$c = $a + $b;

if ($c < 20) {
trigger_error("Sum is less than 20.", E_USER_ERROR);
      echo "This will not be printed!";
}

?>

This adds a similar log entry to what we saw previously, but with an error level, plus the conventional error source information (log file output below):

[01-Mar-2021 01:16:56 UTC] PHP Fatal error:  Sum is less than 20. in code/my-php/index.php on line 10

syslog()

You can also choose to directly send an error message to the system’s log using the syslog() function.

syslog (int $priority, string $message) : bool

The first argument is the error’s priority level – LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_ALERT, LOG_EMERG, etc. (more about it here).  The second argument is the actual message’s text. This is how the function can be used:

<?php
// opening logger connection
openlog('myApp', LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER | LOG_PERROR
); // more information about params in documentation

syslog(LOG_WARNING, "My error message!");

closelog();
?>

This should reflect in your system’s logger (usually in /var/log/syslog) as:

Mar 1 13:27:15 zsh php: My error message! 

set_error_handler()

To customize the handling of all the user-defined errors throughout your code, PHP allows you to specify a custom error handler function to override the default handling of errors. This makes it easy for organizations to modify how they want their errors logged, the corresponding error messages send method, and much more. The set_error_handler() function helps with this.

set_error_handler (callable $error_handler, int $error_types=E_ALL | E_STRICT) : mixed

It takes as an argument our custom error handler function, which will define the handling of our errors, and look something like this:

handler (int $errno, string $errstr, string $errfile=?, int $errline=?, array $errcontext=?) : bool

This takes in many parameters like the error number, error string, corresponding file, etc. Let’s understand this better using the same previous example:

<?php
// custom error handler function ->
function myErrorHandler($errno, $errstr, $errfile, $errline, $errcontext){
    $message = date("Y-m-d H:i:s - "); // timestamp in error message
    $message .= "My Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, n"; // custom error message
    $message .= "Variables:" . print_r($errcontext, true) . "rn";
   
    error_log($message, 3, "/path/my-error-file.log");
    die("There was a problem, please try again."); // exit code
}

set_error_handler("myErrorHandler");

$a = 5;
$b = 10;
$c = $a + $b;

if ($c < 20) {
trigger_error("Sum is less than 20.", E_USER_WARNING);
}

echo "This will not be printed!";
?>

Here, we define a custom error handler function where we modify the error message a bit, log it, and exit the code. Then, when we use the trigger_error() function, its logging is handled by the above function, which takes care of the rest. This is what the output in the log file looks like:

2021-03-01 06:58:07 - My Error: [512], Sum is less than 20. in code/my-php/index.php on line 22,

Variables:Array

(

   [a] => 5

   [b] => 10

   [c] => 15

)

As you can see, this can be used to fully customize error logging in applications, allowing organizations to prioritize aspects of errors and contexts that are more important for their application.

Popular PHP Logging Libraries 

Thanks to the huge PHP community support on the internet, there have been very many logging libraries that aim to provide more functionality and ease the overall process for developers and organizations. Each of the renowned PHP frameworks that you must have heard of come equipped with logging libraries built-in. There are also now logging standards established, like the PSR-3 (PHP Standards Recommendation) logger interface, that defines a standardized interface to follow for logging libraries. 

Below is a list of some of the most popular logging libraries in PHP:

  • Monolog
  • Analog
  • KLogger
  • Log4PHP

Feel free to check these out to see what default error logging in PHP is missing out on.

Wrapping Up 

In this post, we covered everything about errors and logging in PHP. We discussed the importance of logging mechanisms in your application, looked at the different types of errors in PHP, and explored the various configuration options and PHP functions that we can use to log errors effectively.

Now that you have a decent understanding of everything, go ahead and start implementing error logging for your application! It doesn’t matter if you are working on a small project where things might seem under control even without log files. Logging your errors is considered one of the top “best practices” in software development that becomes exponentially more important as your applications grow and scale.

To learn more about logging in PHP in general, feel free to check out the Tutorial: Log to Console in PHP on our blog!

To up your application monitoring game by identifying bottlenecks and gaining effective application performance insights, check out ScoutAPM to get started with a 14-day free trial!

Happy coding!

No one likes to see errors on their website. Not only do they look bad to visitors and potential customers, but they also indicate that something’s wrong. But they’re, unfortunately, an inevitable part of running a site. The good news is that following a few best practices and being proactive can dramatically reduce the number of errors you experience. 

One way to monitor potential site issues — or troubleshoot existing ones — is to keep and review an error log. Let’s dive into this a bit more.

What is error logging and why is it important?

Error logging is the process of tracking and monitoring issues that occur on a website. This is usually done with a record of simple text files that live on your web server and are updated whenever an error occurs. Error logs are used to identify the number of problems that occur, provide details about each one, and show when it took place.

How to enable error logging

To enable error logging on your WordPress site, you’ll need sFTP access, available with WordPress.com plugin-enabled plans. This allows you to edit your website files remotely. In this case, you’ll be working with the wp-config.php file, which holds the basic configuration settings for your website.

A word of warning: you should only use sFTP and edit your wp-config.php file if you feel comfortable doing so. Mistakes can cause catastrophic errors on your website. If you don’t have experience changing these types of files, you may want to hire a developer or reach out to WordPress.com support for help.

1. Connect to your website via sFTP

You’ll need to start by enabling sFTP on your site. Go to My Site(s) → Settings → Hosting Configuration and click the Enable SFTP button.

Then, you’ll see your sFTP login details: URL, Port Number, Username, and Password. You’ll need to input these into FTP software, like FileZilla, to access your site. Follow these detailed instructions to connect to your WordPress.com website.

2. Find and download your wp-config.php file

Navigate to your wp-config.php file. This sits in the root directory of your file structure, alongside folders such as wp-content. Download this file, so you have a backup copy on hand.

3. Edit the wp-config.php file

Edit your wp-config.php file using a text editor such as Notepad.

Look for define( ‘WP_DEBUG’, false ); and replace this text with the following:

define( ‘WP_DEBUG’, true );

if ( WP_DEBUG ) {

        @error_reporting( E_ALL );

        @ini_set( ‘log_errors’, true );

        @ini_set( ‘log_errors_max_len’, ‘0’ );

        define( ‘WP_DEBUG_LOG’, true );

        define( ‘WP_DEBUG_DISPLAY’, false );

        define( ‘CONCATENATE_SCRIPTS’, false );

        define( ‘SAVEQUERIES’, true );

}

You’ve now successfully enabled error logging. You should only have this feature turned on while troubleshooting. Otherwise, it can leave your site more vulnerable to hacking attempts. To disable logging, simply delete the code you just added and restore the following:

define( ‘WP_DEBUG’, false );

How to view the error log manually

Once the log is enabled, you’ll need to load your website to trigger any error codes. Those codes are stored in a file called debug.log, which you can access via sFTP by following the same steps as above. 

You can find the debug.log file inside of the wp-content folder. If there are errors, the file will appear. However, if there aren’t any errors, then you won’t see it at all — congratulations!

Once you find the file, download it to your computer to view the full log, using a text editing software like Notepad. It will look something like this:

This file will provide valuable information that will point you, or your developer, to the source of your problem. 

How to view the error log using a plugin 

Using a plugin to find your error log can be an easier and faster method, depending on your level of experience. In the WordPress dashboard, click on Plugins → Add New. Search for “Error Log Monitor” and click Install → Activate.

This plugin installs a widget on your WordPress dashboard that allows you to access your error log. If you haven’t enabled error logging correctly, the widget will display instructions on how to do so. However, you should ignore these instructions, as they’re incorrect for a WordPress.com installation. Instead, use the ones listed above.

If you can’t see the dashboard widget, click on the Screen options tab at the top of the WordPress dashboard and ensure that “PHP error log” is checked.

How to find the plugin or theme that’s causing an error

Error logs are not inherently easy to read, but they do give insightful information into the cause of an error.

Typically, each line in your error log will display a message, alongside the date and time it happened and the file in which the error occurred. It also lists the line number where the error is located. For example:

Apr 20, 15:08:59

Notice: Undefined index: fg2 in /wordpress/themes/pub/varia/functions.php on line 166

Let’s break this down. First of all, there’s the date and time of the error: April 20, 15:08:59. This helps you determine if this was a one-off glitch or a recurring issue.

Then, you can see the type of error that’s been logged. Here are a few common types of error you may see here:

  • Notice. These are more warnings than errors, as they don’t actually stop your website code from executing. While you should still address a notice, your site will most likely still function, although potentially not as designed.
  • Parse error. This is typically the result of a mistake in the syntax of the underlying PHP code of the website (often in a theme or plugin). Parse errors include things like missing semicolons, parentheses, and other similar mistakes. A parse error will stop executing code when it hits the problem, so your site may look visibly broken or not function as intended.
  • Fatal error. This is often caused by undefined functions or classes, like a typo or poor coding practice. You can avoid it by using high-quality code, along with functions such as class_exists or function_exists.

In this case, the error is a notice.

Next, we see the error itself. In the example above the error is “undefined index.” This is followed by the specific location of the problem. In the above example, the error is occurring with the functions.php file of the Varia theme.

How to fix errors

Now that you can see your errors, it’s time to troubleshoot. Here’s a few things you can try:

  • If you’re a developer and the error is in your custom code, go to the line number in the log entry and work to debug.
  • If the error is within a theme or plugin, start by checking for any available updates. Keeping your plugins and themes up to date is critical for avoiding bugs and maintaining website security. Once you’ve applied any updates, re-check the error log to see if there are any new entries. If the error still exists, reach out to the plugin author or consider switching to an alternative. 
  • The error may also be caused by a conflict between two plugins. Try using the WordPress troubleshooting mode to fix this problem.
  • If the problem occurred immediately after installing or updating a plugin, deactivate it to see if the error persists. If it doesn’t, the plugin is the likely cause and you may want to find an alternative. If the error occured after a core update, you may need to manually deactivate plugins to find the source.

Troubleshooting with the WordPress error log

WordPress, like any software, may occasionally run into problems. It may seem confusing to find and fix those problems, but the error log can be a huge help! It enables you to learn valuable information that can help you troubleshoot and solve site errors in a timely manner.

To avoid errors, always use well-maintained plugins and themes, and keep on top of updates. Need more help? If you have a WordPress plugin-enabled plan, you benefit from world-class Happiness Engineers that can provide guidance.

The “cannot read property of undefined” error occurs when you attempt to access a property or method of a variable that is undefined. You can fix it by adding an undefined check on the variable before accessing it.

The "cannot read property of undefined" error in JavaScript.

Depending on your scenario, doing any one of the following might resolve the error:

  1. Add an undefined check on the variable before accessing it.
  2. Access the property/method on a replacement for the undefined variable.
  3. Use a fallback result instead of accessing the property.
  4. Check your code to find out why the variable is undefined.

1. Add undefined check on variable

To fix the “cannot read property of undefined” error, check that the value is not undefined before accessing the property.

For example, in this code:

const auth = undefined;

console.log(auth); // undefined

// ❌ TypeError: Cannot read properties of undefined (reading 'user')
console.log(auth.user.name);

We can fix the error by adding an optional chaining operator (?.) on the variable before accessing a property. If the variable is undefined or null, the operator will return undefined immediately and prevent the property access.

const auth = undefined;

console.log(auth); // undefined

// ✅ No error
console.log(auth?.user?.name); // undefined

The optional chaining operator also works when using bracket notation for property access:

const auth = undefined;

console.log(auth); // undefined

// ✅ No error
console.log(auth?.['user']?.['name']); // undefined

This means that we can use it on arrays:

const arr = undefined;

console.log(arr?.[0]); // undefined

// Array containing an object
console.log(arr?.[2]?.prop); // undefined

Note

Before the optional chaining was available, the only way to avoid this error was to manually check for the truthiness of every containing object of the property in the nested hierarchy, i.e.:

const a = undefined;

// Optional chaining
if (a?.b?.c?.d?.e) {
  console.log(`e: ${e}`);
}

// No optional chaining
if (a && a.b && a.b.c && a.b.c.d && a.b.c.d.e) {
  console.log(`e: ${e}`);
}

2. Use replacement for undefined variable

In the first approach, we don’t access the property or method when the variable turns out to be undefined. In this solution, we provide a fallback value that we’ll access the property or method on.

For example:

const str = undefined;

const result = (str ?? 'old str').replace('old', 'new');

console.log(result); // 'new str'

The null coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.

console.log(5 ?? 10); // 5
console.log(undefined ?? 10); // 10

The logical OR (||) operator can also do this:

console.log(5 || 10); // 5
console.log(undefined || 10); // 10

3. Use fallback value instead of accessing property

Another way to solve the “cannot read property of undefined” error is to avoid the property access altogether when the variable is undefined and use a default fallback value instead.

We can do this by combining the optional chaining operator (?.) and the nullish coalescing operator (??).

For example:

const arr = undefined;

// Using "0" as a fallback value
const arrLength = arr?.length ?? 0;

console.log(arrLength); // 0


const str = undefined;

// Using "0" as a fallback value
const strLength = str?.length ?? 0;

console.log(strLength); // 0

4. Find out why the variable is undefined

The solutions above are handy when we don’t know beforehand if the variable will be undefined or not. But there are situations where the “cannot read property of undefined” error is caused by a coding error that led to the variable being undefined.

It could be that you forgot to initialize the variable:

let doubles;

let nums = [1, 2, 3, 4, 5];

for (const num of nums) {
  let double = num * 2;

  // ❌ TypeError: cannot read properties of undefined (reading 'push')
  doubles.push(double);
}

console.log(doubles);

In this example, we call the push() method on the doubles variable without first initializing it.

let doubles;

console.log(doubles); // undefined

Because an uninitialized variable has a default value of undefined in JavaScript, accessing a property/method causes the error to be thrown.

The obvious fix for the error, in this case, is to assign the variable to a defined value.

// ✅ "doubles" initialized before use
let doubles = [];

let nums = [1, 2, 3, 4, 5];

for (const num of nums) {
  let double = num * 2;

  //  push() called - no error thrown
  doubles.push(double);
}

console.log(doubles); // [ 2, 4, 6, 8, 10 ]

Another common mistake that causes this error is accessing an element from an array variable before accessing an Array property/method, instead of accessing the property/method on the actual array variable.

const array = [];

// ❌ TypeError: Cannot read properties of undefined (reading 'push')
array[0].push('html');
array[0].push('css');
array[0].push('javascript');

console.log(array);

Accessing the 0 property with bracket indexing gives us the element at index 0 of the array. The array has no element, so arr[0] evaluates to undefined and calling push() on it causes the error.

To fix this, we need to call the method on the array variable, not one of its elements.

const array = [];

// ✅ Call push() on "array" variable, not "array[0]"
array.push('html');
array.push('css');
array.push('javascript');

console.log(array); // [ 'html', 'css', 'javascript' ]

Conclusion

In this article, we saw some helpful ways of resolving the “cannot read property of undefined” error in JavaScript. They might not resolve the error totally in your case, but they should assist you during your debugging.

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

Вступление

Формат журнала ошибок [error_log] имеет относительно свободную и описательную форму. Однако, в журнале есть определенная информация, которая содержится в большинстве записи журнала ошибок и которая может помочь разобраться в причинах ошибок.

Расшифруем, например, такое сообщение

Tue Jul 09 13:12:45 2013] [error] [client 62.205.136.204] PHP Notice: Undefined property: plgSystemExtLinks::$_EXTLINKS_REDIRECT in /home/login/domains/example.edu/public_html/plugins/system/extlinks.php on line 71

1.Временная метка

Дата и время ошибки, следующего вида [Tue Jul 09 13:12:45 2013]

2.Серьезность ошибки

В примере [error]. Серьезность ошибки можно посмотреть в таблице взятой из документации Apache. Серьезность ошибки показана в направлении ослабления значимости.

Серьезность

Описание

Пример

emerg

Чрезвычайные ситуации — система не работоспособна

«Child cannot open lock file. Exiting»

«Child не может открыть файл блокировки. Выход»

alert

Необходимо принять меры немедленно.

«getpwuid: couldn’t determine user name from uid»

«не удалось определить имя пользователя из …»

crit

Критические условия.

«socket: Failed to get a socket, exiting child»

» Не удалось получить порт , при выходе Child»

error

Ошибка в условиях.

«Premature end of script headers»

«Преждевременный конец сценария заголовков»

warn

Предупреждение

«child process 1234 did not exit, sending another SIGHUP»

«Дочерний процесс 1234 не выходил, посылая другой SIGHUP»

notice

Нормальное, но важное предупреждение

«httpd: caught SIGBUS, attempting to dump core in …»

«httpd: пойманные SIGBUS,в дампе памяти …»

info

Информация

«Server seems busy, (you may need to increase StartServers, or Min/MaxSpareServers)…»

«Сервер кажется перегруженным , (вы можете увеличить StartServers или Min / Max SpareServers) …»

debug

Уровень отладки сообщений

«Opening config file …»

«Открытие файла конфигурации …»

3.Клиент

[client 62.205.136.204] IP адрес клиента вызвавшего ошибку.

4.Ответ сервера

PHP Notice: Undefined property: plgSystemExtLinks::$_EXTLINKS_REDIRECT in /home/Login_chost/domains/tourru.ru/ public_html/plugins/system/extlinks.php on line 71

Этот короткий описательный ответ сервера, по какой причине сервер присвоил операции значение [error].

Как расшифровать причину ошибки

Чтобы расшифровать причину ошибки, ее для начала нужно перевести.

Замечание PHP:Неопределенно право собственности:

plgSystemExtLinks. Это системный плагин, который есть на сайте.

Путь в файловой системе запрашиваемых документов. В примере запрашиваемый документ это файл плагина, который и вызвал ошибку типа [error]: /home/Login_chost/domains/example.edu/ public_html/plugins/system/extlinks.php в строке 71.

Сама ошибка:

[$_EXTLINKS_REDIRECT]

С расшифровками описаний ошибок ситуация не простая. Так как запись в журнале носит описательный характер, то чтобы ее понять, нужна практика и знание своего сайта.

Приведенная ошибка на первый взгляд это ошибка неудавшейся попытки плагина Extralinks выполнить какое-то перенаправление из-за ошибки в условиях. Дальше, на сайте смотрю, что это за плагин. Это плагин Joomla1.5 для экранирования внешних ссылок.

Можно продолжать разбираться дальше, шаг за шагом. Но эта ошибка не привела к фатальной ошибке, то и углубляться дальше,в этой статье, нет смысла.

Если же в этот промежуток времени сайт, например «рухнул», то для восстановления сайта можно было бы попробовать отключить этот плагин.

Еще один пример записи в логе ошибок Apache:

Wed Jul 10 09:06:59 2013] [error] [client 93.190.138.105] PHP Notice: Trying to get property of non-object in /home/login/domains/example.edu/public_html /modules/mod_junewsultra/mod_junewsultra.php on line 85, referer: http://domains.checkparams.com/index.php?q=example.edu

Информация сервера : PHP Notice: Trying to get property of non-object in

Ошибка условий. PHP Примечание: при попытке получить содержание в модуле Junewsultra (mod_junewsultra) произошла переадресация в другой URL.

©Joomla-abc.ru

Другие ошибки Joomla

Ошибки Joomla

Home / Log PHP errors with log_errors and error_log

PHP errors are by default logged to the web server’s error log file (at least they are with the default setup on most Linux distros) but it is also possible to instead log PHP errors to a file of your choice. This is useful on production websites so you can periodically check for errors and fix them in a location other than the default webserver error log file.

The log_errors configuration option is a boolean option. To log to an error log file specified with the error_log configuration option set this to 1.

error_log

The error_log configuration option is a string and is the filename of where to log errors. It can contain either a relative path or an absolute path as part of the filename. If «syslog» is used it is logged to to the system logger (syslog on *nix and the Event Log on Windows).

Set error logging with ini_set()

Although this is not ideal you can use the ini_set() function to set the above configuration options to log errors. It is not an ideal solution because it will not log any errors if the script has parse errors and cannot be run at all. For example:

ini_set("log_errors", 1);
ini_set("error_log", "/path/to/php-error.log");

Set error logging in .htaccess and virtualhost directives

This is a better option because it will log the errors even if there’s a parsing error in your script.

php_value log_errors 1
php_value error_log /path/to/php-error.log

Example error log data

A couple of example lines from an error log are as follows:

[13-May-2009 21:54:04] PHP Notice:  Undefined variable: x in /common/websites/test/error-log.php on line 6
[13-May-2009 21:54:09] PHP Parse error:  syntax error, unexpected '}' in /common/websites/test/error-log.php on line 5

Error log must be writable by the web server

The error log will be written to as the user the web server runs as so it must be writeable by that user. In most cases you’ll probably need to make it world-writeable to be able to do this. On a *nix server this is 0666 file permissions.

Conclusion

It’s easy to set up a PHP error log using the log_errors and error_log configuration options. This can be set up on a website by website basis and you could potential combine it with a daily process to email errors to the webmaster (if there are any) on a daily basis. I’ll cover doing this in a later post.

(PHP 4, PHP 5, PHP 7, PHP 8)

error_logОтправляет сообщение об ошибке заданному обработчику ошибок

Описание

error_log(
    string $message,
    int $message_type = 0,
    ?string $destination = null,
    ?string $additional_headers = null
): bool

Список параметров

message

Сообщение об ошибке, которое должно быть логировано.

message_type

Определяет куда отправлять ошибку.
Возможны следующие значения:

Типы журналов error_log()

0 Сообщение message отправляется в системный регистратор PHP, используя
механизм логирования операционной системы, или файл, в зависимости от значения директивы
error_log
в конфигурационном файле. Это значение по умолчанию.
1 Сообщение message отправляется электронной почтой на адрес, установленный в параметре
destination. Это единственный тип сообщения, где используется четвёртый параметр
additional_headers.
2 Больше не используется.
3 message применяется к указанному в
destination файлу. Перенос строки автоматически не добавляется в конец
message.
4 Сообщение message отправляется напрямую в обработчик
логера SAPI.
destination

Назначение. Устанавливается в зависимости от параметра
message_type.

additional_headers

Дополнительные заголовки. Используется, когда значение параметра message_type
1.
Данный тип сообщения использует ту же внутреннюю функцию, что и
mail().

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Если message_type равен нулю, функция всегда возвращает true,
независимо от того, может ли ошибка логироваться или нет.

Список изменений

Версия Описание
8.0.0 Параметр destination и
additional_headers теперь допускают значение null.

Примеры

Пример #1 Примеры использования error_log()


<?php
// Отправляет уведомление посредством серверного лога, если мы не можем
// подключиться к базе данных.
if (!Ora_Logon($username, $password)) {
error_log("База данных Oracle недоступна!", 0);
}
// Уведомить администратора по электронной почте, если невозможно выделить ресурсы для FOO
if (!($foo = allocate_new_foo())) {
error_log("Большая проблема, мы выпали из FOO!", 1,
"operator@example.com");
}
// другой способ вызвать error_log():
error_log("Вы ошиблись!", 3, "/var/tmp/my-errors.log");
?>

Примечания

Внимание

error_log() не является бинарно-безопасной функцией. message обрезается по null-символу.

Подсказка

message не должен содержать null-символ. Учтите, что message может передаваться в файл, по почте, в syslog и т.д. Используйте подходящую преобразующую или экранирующую функцию, base64_encode(), rawurlencode() или addslashes() перед вызовом error_log().

kevindougans at gmail dot com

12 years ago


Advice to novices: This function works great along with "tail" which is a unix command to watch a log file live. There are versions of Tail for Windows too, like Tail for Win32 or Kiwi Log Viewer.

Using both error_log() and tail to view the php_error.log you can debug code without having to worry so much about printing debug messages to the screen and who they might be seen by.

Further Note: This works even better when you have two monitors setup. One for your browser and IDE and the other for viewing the log files update live as you go.


Sion

4 years ago


DO NOT try to output TOO LARGE texts in the error_log();

if you try to output massive amounts of texts it will either cut of the text at about 8ooo characters (for reasonable massive strings, < 32 K characters) or (for insanely massive strings, about 1.6 million characters) totally crash without even throwing an error or anything (I even put it in a try/catch without getting any result from the catch).

I had this problem when I tried to debug a response from a wp_remote_get(); all of my error_log() worked as they should, except for ONE of them... (-_-)
After about a day of debugging I finally found out why & that's why I type this.

Apparently the response contained a body with over 1.6 million chars (or bytes? (whatever strlen() returns)).

If you have a string of unknown length, use this:
$start_index = 0;
$end_index = 8000;
error_log( substr( $output_text , $start_index , $end_index ) );


frank at booksku dot com

16 years ago


Beware!  If multiple scripts share the same log file, but run as different users, whichever script logs an error first owns the file, and calls to error_log() run as a different user will fail *silently*!

Nothing more frustrating than trying to figure out why all your error_log calls aren't actually writing, than to find it was due to a *silent* permission denied error!


i dot buttinoni at intandtel dot com

14 years ago


Be carefull. Unexpected PHP dies when 2GByte of file log reached (on systems having upper file size limit).
A work aorund is rotate logs :)

php at kennel17 dot NOSPAM dot co dot uk

17 years ago


It appears that the system log = stderr if you are running PHP from the command line, and that often stderr = stdout.  This means that if you are using a custom error to both display the error and log it to syslog, then a command-line user will see the same error reported twice.

Anonymous

19 years ago


when using error_log to send email, not all elements of an extra_headers string are handled the same way.  "From: " and "Reply-To: " header values will replace the default header values. "Subject: " header values won't: they are *added* to the mail header but don't replace the default, leading to mail messages with two Subject fields.

<?php

error_log

("sometext", 1, "zigzag@my.domain",
 
"Subject: FoonFrom: Rizzlas@my.domainn");?>

---------------%<-----------------------
To: zigzag@my.domain
Envelope-to: zigzag@my.domain
Date: Fri, 28 Mar 2003 13:29:02 -0500
From: Rizzlas@my.domain
Subject: PHP error_log message
Subject: Foo
Delivery-date: Fri, 28 Mar 2003 13:29:03 -0500

sometext
---------------%<---------------------

quoth the docs: "This message type uses the same internal function as mail() does." 

mail() will also fail to set a Subject field based on extra_header data - instead it takes a seperate argument to specify a "Subject: " string.

php v.4.2.3, SunOS 5.8


russ at russtanner dot com

3 years ago


You can easily filter messages sent to error_log() using "tail" and "grep" on *nix systems. This makes monitoring debug messages easy to see during development.

Be sure to "tag" your error message with a unique string so you can filter it using "grep":

In your code:

error_log("DevSys1 - FirstName: $FirstName - LastName: $Lastname");

On your command line:

tail -f /var/log/httpd/error_log | grep DevSys1

In this example, we pipe apache log output to grep (STDIN) which filters it for you only showing messages that contain "DevSys1".

The "-f" option means "follow" which streams all new log entries to your terminal or to any piped command that follows, in this case "grep".


Matthew Swift

3 years ago


Relative paths are accepted as the destination of message_type 3, but beware that the root directory is determined by the context of the call to error_log(), which can change, so that one instance of error_log () in your code can lead to the creation of multiple log files in different locations.

In a WordPress context, the root directory will be the site's root in many cases, but it will be /wp-admin/ for AJAX calls, and a plugin's directory in other cases. If you want all your output to go to one file, use an absolute path.


paul dot chubb at abs dot gov dot au

14 years ago


When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:

LogToApache($Message) {
        $stderr = fopen('php://stderr', 'w');
        fwrite($stderr,$Message);
        fclose($stderr);
}


SJL

15 years ago


"It appears that the system log = stderr if you are running PHP from the command line"

Actually, it seems that PHP logs to stderr if it can't write to the log file. Command line PHP falls back to stderr because the log file is (usually) only writable by the webserver.


stepheneliotdewey at GmailDotCom

15 years ago


Note that since typical email is unencrypted, sending data about your errors over email using this function could be considered a security risk. How much of a risk it is depends on how much and what type of information you are sending, but the mere act of sending an email when something happens (even if it cannot be read) could itself imply to a sophisticated hacker observing your site over time that they have managed to cause an error.

Of course, security through obscurity is the weakest kind of security, as most open source supporters will agree. This is just something that you should keep in mind.

And of course, whatever you do, make sure that such emails don't contain sensitive user data.


p dot lhonorey at nospam-laposte dot net

16 years ago


Hi !

Another trick to post "HTML" mail body. Just add "Content-Type: text/html; charset=ISO-8859-1" into extra_header string. Of course you can set charset according to your country or Env or content.

EG: Error_log("<html><h2>stuff</h2></html>",1,"eat@joe.com","subject  :lunchnContent-Type: text/html; charset=ISO-8859-1");

Enjoy !


eguvenc at gmail dot com

14 years ago


<?php

//Multiline error log class

// ersin güvenç 2008 eguvenc@gmail.com

//For break use "n" instead 'n'
Class log {

 
//

 
const USER_ERROR_DIR = '/home/site/error_log/Site_User_errors.log';

  const
GENERAL_ERROR_DIR = '/home/site/error_log/Site_General_errors.log';
/*

   User Errors...

  */

   
public function user($msg,$username)

    {

   
$date = date('d.m.Y h:i:s');

   
$log = $msg."   |  Date:  ".$date."  |  User:  ".$username."n";

   
error_log($log, 3, self::USER_ERROR_DIR);

    }

   
/*

   General Errors...

  */

   
public function general($msg)

    {

   
$date = date('d.m.Y h:i:s');

   
$log = $msg."   |  Date:  ".$date."n";

   
error_log($msg."   |  Tarih:  ".$date, 3, self::GENERAL_ERROR_DIR);

    }

}

$log = new log();

$log->user($msg,$username); //use for user errors

//$log->general($msg); //use for general errors

?>

franz at fholzinger dot com

17 years ago


In the case of missing your entries in the error_log file:
When you use error_log in a script that does not produce any output, which means that you cannot see anything during the execution of the script, and when you wonder why there are no error_log entries produced in your error_log file, the reasons can be:
- you did not configure error_log output in php.ini
- the script has a syntax error and did therefore not execute

daniel dot fukuda at gmail dot com

13 years ago


If you have a problem with log file permission *silently*
it's best to leave error_log directive unset so errors will be written in your Apache log file for current VirtualHost.

Anonymous

2 years ago


Depending on the error, you may also want to add an error 500 header, and a message for the user:

$message =  'Description of the error.';
error_log($message);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit($message);


Robert Chapin

4 years ago


When error_log() unexpectedly uses stdout, you should check if the php.ini value for error_log is empty in your CLI environment.  Something as simple as this might restore expected behavior:

<?php ini_set('error_log', 'error_log'); ?>


kazezb at nospam dot carleton dot edu

17 years ago


It appears that error_log() only logs the first line of multi-line log messages. To log a multi-line message, either log each line individually or write the message to another file.

Anonymous

13 years ago


After scouring the internet for getting event logging to
work in syslog on Windows 2003, I found the following
from this post and was able to successfully get Windows
Event Viewer to log PHP errors/notices:

http://forums.iis.net/p/1159662/1912015.aspx#1913338

   1. Copy the PHP 5 binaries to "C:php".
   2. Right-click My Computer and select Properties to bring
up the Computer Properties dialog. Switch to the Advanced
tab and click Environment Variables. Find the system
environment variable PATH, edit it and add ";C:php"
(without the quotes) to the end.
   3. Make sure that the configuration file "php.ini" resides
in the directory "C:php" and contains the correct path
settings.
   4. DELETE any old "php.ini" files from "C:WINDOWS"
and other directories.
   5. Open REGEDIT, navigate to the key
"HKLMSOFTWAREPHP" and DELETE the string value
"IniFilePath" from there. It is outdated and no longer
necessary!
   6. Modify NTFS security permissions of the directory
"C:php" to give Read and Execute permissions to (1) the
IIS Guest Account and (2) the group IIS_WPG.
   7. Modify NTFS security permissions of the directories
"C:phpsession" and "C:phpupload" to give additional
Modify permissions to (1) the IIS Guest Account and (2)
the group IIS_WPG.
   8. Navigate to the registry key
"HKLMSYSTEMCurrentControlSetServicesEventlog
Application" and edit the value "CustomSD" there. Find
the substring "(D;;0xf0007;;;BG)" which Denies access to
the application event log for Builtin Guest accounts (like
the IIS Web User account) and replace this substring with
"(A;;0x3;;;BG)" which allows read and write access. Please
pay attention to leave the rest of the security string intact.
Damaging this value can have dangerous effects!
   9. Create or update the registry key
"HKLMSYSTEMCurrentControlSetServicesEventlogApplication
PHP-5.2.0" (adapt the last to your version part
if necessary) with the following values:

          * "EventMessageFile" (REG_EXPAND_SZ) = "C:phpphp5ts.dll"

          * "TypesSupported" (REG_DWORD) = 7


Logback — программная установка имени файла журнала

ВLogback легко задать имя файла журнала программно:

  1. Вlogback.xml объявляет переменную типа${log.name}

  2. В Java установите переменную черезSystem.setProperty("log.name", "abc")

1. Полный пример

1.1 A logback file, we will set the ${log.name} variable later.

src/main/resources/logback.xml


    
    

    

    
        ${USER_HOME}/${log.name}.error
        
            %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
        
    

    
        ${USER_HOME}/${log.name}-${bySecond}.log
        
            %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{35} - %msg%n
        
    

    
        
    

    
        
    

    
        
    

1.2 In Java, just set the file name via System.setProperty

AntRunApp.java

package com.example.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AntRunApp {

    private final Logger logger = LoggerFactory.getLogger(AntRunApp.class);

    public static void main(String[] args) {

        //Set this before the logger start.
        System.setProperty("log.name", "example");

        AntRunApp obj = new AntRunApp();
        obj.start();

    }

    private void start() {

        logger.debug("------ Starting Ant------");

        //...
    }

}

Выход

Debug log file path
/home/example/ant/logs/example-20150323.221959.log

Error log file path
/home/example/ant/logs/example.error

2. log.name.rir_IS_UNDEFINED.log

2.1 A common error, normally it is caused by the static logger. Например.

AntRunApp.java

package com.example.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AntRunApp {

    // static, this logger will be initialized before the program is run.
    // All logs will be redirected to log.name.rir_IS_UNDEFINED.log
    private static final Logger logger = LoggerFactory.getLogger(AntRunApp.class);

    private void start() {

        System.setProperty("log.name", "example");

        logger.debug("------ Starting Ant------");

        //...
    }

}

To fix it, просто удалите типstatic.

2.2 If you logs before the System.setProperty, this will also cause the common Logback variable UNDEFINED error.

AntRunApp.java

package com.example.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AntRunApp {

    private final Logger logger = LoggerFactory.getLogger(AntRunApp.class);

    private void start() {

        //Please set the log name first!
        logger.debug("------ Starting Ant------");

        System.setProperty("log.name", "example");

    }

}

Понравилась статья? Поделить с друзьями:
  • Undefined an unexpected error has occurred перевод
  • Undefined 1 syntax error
  • Undeclared identifier delphi как исправить
  • Undeclared first use in this function error in c
  • Und ошибка на машинке haier