How to log to file

How to log to file

How to log to a file in Java?

How can I create logs (error, info log and benchmarking) with the java Logger which are written to disk, i.e. to a file? I would like to have each logging entry on one line.

Thank you in advance.

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

find below a simple example how to use the Java core java.util.logging.Logger. If there is no compulsory reason to use it, I woud suggest you to have a look on one of the Java logging frameworks around (they are most of the time easier to configure).

The Java world offers a variety of choices of frameworks to help with the chore of logging.

Logging can get complicated. You may want to disable or enable log messages of various levels of severity. You may want to configure logging during development to connect to the console in your IDE while configuring differently for testing and yet different again for production. You may want logging to go to text files, to message queues, to databases, to trigger email or SMS text messages, set off alarm lights, who knows what. A flexible logging framework can help with all that.

java.util.logging

One is bundled with Java 4 and later, in the java.util.logging package. This other answer covers this option. Discussed here on the Oracle site. While useful, many folks consider this less than optimal.

log4j

Perhaps the best known is log4j. This framework was one of the first robust flexible logging frameworks invented. This product was originally published by IBM and later donated to the Apache foundation.

slf4j & Logback

One of the principal inventors of log4j, Ceki Gülcü, took what he learned from that project to start again from scratch. The result is a pair of products. One, slf4j, is an interface for logging, to be used as a façade in front of a separate implementation. Actually, slf4j includes a very simple implementation, aptly named SimpleLogger, but you will probably want to use another backing implementation in production.

Logback

The other project launched by Gülcü is Logback. This product directly implements the slf4j interface. Logback is full-featured and robust. Think of it as a next-generation of log4j, but fresh and re-architected. Gülcü built slf4j and Logback in tandem, each influencing the other, intended to be a great combination.

However, you Logback is not your only choice. That was the very purpose in creating slf4j, to give you a choice of implementations while using only slf4j calls in your code. This way you can change the backing implementation without making any changes all those logging calls throughout your project’s source code.

Another direct implementation of slf4j is written in Scala, AVSL (A Very Simple Logger).

slf4j Adapters

Adapters enable you to use other logging frameworks that were not originally designed for the slf4 interface. At least two are available, one for the java.util.logging framework and another for log4j.

Recommendation

I strongly recommend slf4j. The idea of an interface separate from various possible backends just makes sense to me. Especially given that logging means so many lines of code spread out all over all your code. Being able to swap back-ends without disturbing your source code is a wonderful luxury. Furthermore, slf4j was created based on much past experience and is itself well-worn now for years, so it should be a reliable trustworthy choice.

If you have legacy projects using either log4j or java.util.logging, you can install slf4j with an adapter now for new logging calls. You may choose to gradually replace the old logging calls with new slf4j calls, giving you the freedom to eventually change implementations if you ever see the need.

For new projects you can use slf4j and probably choose Logback as the backing implementation. You can sleep easier knowing that if Logback ever faltered you could switch easily to another implementation.

However, there are ever more choices than I described here. So you may want to shop around further.

error_log

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

error_log — Send an error message to the defined error handling routines

Description

Sends an error message to the web server’s error log or to a file.

Parameters

The error message that should be logged.

Says where the error should go. The possible message types are as follows:

The destination. Its meaning depends on the message_type parameter as described above.

Return Values

Changelog

VersionDescription
8.0.0destination and additional_headers are now nullable.

Examples

Example #1 error_log() examples

Notes

error_log() is not binary safe. message will be truncated by null character.

User Contributed Notes 20 notes

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.

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,

The default seem to be 1024 but can be changed by adjusting the value of the runtime configuration value of ‘log_errors_max_len’.

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!

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.

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»:

On your command line:

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».

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);
>

«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.

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.

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.

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.

stuff

«,1,»eat@joe.com»,»subject :lunch\nContent-Type: text/html; charset=ISO-8859-1″);

//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’ ;

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:

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

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:

How to write to a file, using the logging Python module?

How can I use the logging module in Python to write to a file? Every time I try to use it, it just prints out the message.

12 Answers 12

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

An example of using logging.basicConfig rather than logging.fileHandler()

In order, the five parts do the following:

And you’re good to go.

P.S. Make sure to read the logging HOWTO as well.

Here is two examples, one print the logs (stdout) the other write the logs to a file:

With this example, all logs will be printed and also be written to a file named logs.log

How to log to file. Смотреть фото How to log to file. Смотреть картинку How to log to file. Картинка про How to log to file. Фото How to log to file

I prefer to use a configuration file. It allows me to switch logging levels, locations, etc without changing code when I go from development to release. I simply package a different config file with the same name, and with the same defined loggers.

Here is my code for the log config file

How to log to file. Смотреть фото How to log to file. Смотреть картинку How to log to file. Картинка про How to log to file. Фото How to log to file

here’s a simpler way to go about it. this solution doesn’t use a config dictionary and uses a rotation file handler, like so:

the handlers variable needs to be an iterable. logpath+filename and debug_level are just variables holding the respective info. of course, the values for the function params are up to you.

the first time i was using the logging module i made the mistake of writing the following, which generates an OS file lock error (the above is the solution to that):

How do I log errors and warnings into a file?

How do I turn on all error and warnings and log them to a file, but to set up all of that within the script (not changing anything in php.ini)?

I want to define a file name and so that all errors and warnings get logged into it.

How to log to file. Смотреть фото How to log to file. Смотреть картинку How to log to file. Картинка про How to log to file. Фото How to log to file

8 Answers 8

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Use the following code:

Then watch the file:

Or update php.ini as described in this blog entry from 2008.

How to log to file. Смотреть фото How to log to file. Смотреть картинку How to log to file. Картинка про How to log to file. Фото How to log to file

You can customize error handling with your own error handlers to call this function for you whenever an error or warning or whatever you need to log occurs. For additional information, please refer to the Chapter Error Handling in the PHP Manual

How to log to file. Смотреть фото How to log to file. Смотреть картинку How to log to file. Картинка про How to log to file. Фото How to log to file

Simply put these codes at top of your PHP/index file:

Add this code in file .htaccess (as an alternative to file php.ini or the ini_set function):

How to log to file. Смотреть фото How to log to file. Смотреть картинку How to log to file. Картинка про How to log to file. Фото How to log to file

How to log to file. Смотреть фото How to log to file. Смотреть картинку How to log to file. Картинка про How to log to file. Фото How to log to file

That’s my personal short function

Take a look at the log_errors configuration option in php.ini. It seems to do just what you want to. I think you can use the error_log option to set your own logging file too.

How to Get Started with Logging in PHP

Contents

Logging is an essential and underutilized practice in software development. It’s obvious value is for debugging, but it can also be a resource for deriving various analytics and usage information. When you learn how to log properly, you will be able to adequately track the inner workings of your application so that troubleshooting becomes much more effortless.

In this article, we will discuss the basics of logging in PHP and explore all the logging-related configurations you should know. We will begin by discussing the native logging functions in the language before branching out to examine the logging solutions developed by other PHP users. Here are some of the other things you stand to learn by following through with this article:

Prerequisites

Ensure to have the latest version of PHP installed on your machine before proceeding with this article. The code snippets and command output included in the sections below were all tested and confirmed to be accurate as at PHP v8.x, but they should continue to work with later versions.

What should you log?

Before we discuss how logging works in PHP, let’s briefly examine what you should consider logging when developing your application. Some typical candidates for what to log include the following:

Errors and exceptions. Ensure to log every error and exception that occurs in your application so that you can find the root cause of an issue and fix them quickly.

Incoming requests. When a request is made to an endpoint in your application, you should log that event and include details such as a timestamp, user ID (if any), the endpoint and HTTP method, etc. It is also a good idea to generate a correlation ID at this point such that all other logging calls following from the request will include this ID, making it easier to trace the path of a specific client request in the application.

Any changes to your database, including inserting new data and updating and deleting existing data. You should record what data was changed, who changed it, and when it occurred.

Accessing sensitive information. Whenever sensitive or restricted information is being accessed on the system, a corresponding log entry should be recorded describing who accessed the resource and when.

Logging as much as possible does not mean you should record just anything as irrelevant entries will create noise and make your logs much less helpful. You should also take care never to log anything that would compromise user privacy such as passwords, credit card information, home addresses, phone numbers, or other Personally Identifiable Information (PII).

Understanding logging configurations in PHP

PHP saves all its configuration in a php.ini file whose location depends on your operating system and how you installed PHP. Luckily, there is an easy way to locate the configuration file. Open a new terminal window and run the following command:

The highlighted line above describes where to find the relevant php.ini file you need to edit. Copy the path to the file and open it in your text editor:

This configuration file is enormous, but we only care about a small section. Scroll down to the «Error handling and logging» section or use your text editor’s search function.

Let’s look at some of the common directives in this section that you need to note. You can find a complete list of all available directives in the official documentation. Note that you’ll need to restart your web server after making changes to your php.ini file for the changes to take effect.

E_NOTICE means that all notice-level messages will be omitted.

display_errors : controls whether PHP should output errors to the screen as part of the program’s output or if they should be hidden from view. Keeping this value On is fine in development settings, but it should always be turned Off in production, or end users may see ugly stack traces on your website when an error occurs (see above screenshot).

display_startup_errors : determines whether PHP will output errors that occur during its startup sequence. These errors are hidden by default, but you can turn them on when debugging.

log_errors_max_len : restricts the maximum length of each log record to the specified value in bytes. The default is 1024 bytes, but setting this option to 0 removes the restriction.

Aside from configuring these options directly in the php.ini file, PHP also offers a way override them at runtime. This can be useful in a serverless environment where you don’t have access to the configuration file, or when you are troubleshooting an issue.

You can retrieve the current configuration using the ini_get() function as shown below:

If you wish to override an existing configuration, you can provide a new value using the ini_set() function:

Error levels and constants in PHP

In this section, we’ll examine one of the more obtuse aspects of PHP logging: error level constants. They are conceptually similar to log levels and are used to distinguish the different types of diagnostic messages produced when executing a program.

PHP has an unnecessarily complicated system when it comes to log levels. It uses many different constants to indicate different log levels, and these constants can be roughly classified into three families:

Exploring logging functions in PHP

Now that we’ve examined the PHP logging configuration and its error constants, let’s get into the nitty-gritty of logging in a PHP project. Several logging functions ship with PHP, and they all depend on the configurations discussed in the earlier sections.

To guarantee that you get results consistent with what is described in the sections below, ensure that your logging configuration matches the following values:

Источники информации:

Добавить комментарий

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