I'm developing a web-application using PHP which is on tests by some of my friends. What approach do you recommend me to use in order to know what warnings are they getting but without displaying them using ini_set('display_errors', 1);?
Also, the application will run in a intranet in which I'll not have access remotely.
I was thinking to send daily emails with some information to me, but i don't know which are important facts to be saved. Do you have a article/sample for me? Do you have a better advice for me?
You can log the errors without displaying them.
For example you can do something like:
error_reporting(E_ALL | E_STRICT); //For PHP 6 E_STRICT become part of E_ALL
ini_set('display_errors', 'Off');
ini_set('log_errors', 'On');
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/php.log');
You can also edit PHP.ini or do it with an .htaccess (if on Apache).
If you can't access this log remotely you can make a small PHP application that will send you the log via email.
You can use PHP mail() but a library like PHPMailer will speed things up (and will be easier to use).
Have a CRON job (or something equivalent) fire the email every day (or week or else).
Write an error handler and use set_error_handler to make sure it's called instead of the default one. In that handler, you can do whatever you think is best for your purpose.
If you want to do a daily e-mail, you would save the data to a database or file, and make a cronjob run once a day to send the e-mail with the latest data. I would probably prefer to just save to a logging table in a database, which I can then view via some interface when relevant.
That's not going to catch EVERYTHING, though - all E_WARNING will be caught, but not all other types will be. For example, parse errors can't be caught this way, and if you might want to handle exceptions as well, you should use set_exception_handler.
I think that it's the only possibility.
If you could connect there you could see apache log.
But otherwise. I'm sorry.
My best advice is to read up on PHP's set_error_handler function. It lets you determine exactly what happens whenever some error occurs -- whether you email it, log it, or whatever you want to do.
Now, there are numerous great articles on logging errors in PHP instead of displaying them to the end user. Some random examples, which I found with a 30 second Google search:
http://davidwalsh.name/custom-error-handling-php
http://www.electrictoolbox.com/log-php-errors-log-errors-error-log/
http://www.w3schools.com/php/php_error.asp
There are many ways to handle errors in PHP. Besides the aforementioned, you could rely on the default PHP error logs (by default, PHP use's Apache's error logs, i.e. /var/log/httpd/error_log). However you can modify your php.ini to send the messages to any file you like. You can check that file daily to see what errors occur.
You could also setup a CRONTAB script to read in that file once per day and email it to you, then clear it out.
Again, I'd suggest set_error_handler as a more flexible option.
Related
I am currently capturing script errors as such:
error_reporting(-1) ;
ini_set("log_errors",TRUE) ;
ini_set("error_log","phpErrors.log") ;
But I need a better mechanism of reporting those errors so I don't have to manually go look at log files to see if something was captured. I read about error_log has a built in email function as found here: Send errors message via email using error_log()
Does using this email function in error_log() interfere with logging to the log file? As well, is there a better mechanism for creating alerts (of some type) so I am not getting inundated with error emails? I suppose whatever mechanism I use it will be the same level of alerts/emails - but I just need a better way of getting notified than scrubbing through error logs.
Any recommendations?
When you call error_log, it will do only the action as specified by the second parameter, not both or more than one. So if you say to send an email, it won't log to disk. If the second parameter was a bitmask, that would imply that then. I'm guessing that the intention was for this to be used sporadically with explicit intent each time.
As to "Is there a better mechanism?", that gets subjective, and there is a tipping point with logging that you'll need to determine what is best for you and your project, workflow, team, etc.
Personally, I like Monolog which follows PSR-3 and documents 8 levels of logging, from debug to emergency. Using Monolog you setup "handlers" whose job is to do something with the logs, either write to disk, database, syslog, console, or possibly send an email, SMS or some other third party service. Each handler can be setup with different log levels, so you might log debug and greater to disk, send error or greater to email and emergency to SMS. The customization is completely up to you.
There are other PSR-3 loggers out there, too, and it is really trivial to roll your own if you need something simple, but I would encourage you to look into that general setup.
I have a website working and I would like to add log to be able to monitor if some errors append during the day.
I've search on stackoverflow and on the internet about it and there is a lot of information about logging framework, what to log... but for a beginner it is confusing. I do not know how to start.
Here are my questions :
If I had no info, I would create a .txt file and use file_put_contents in my PHP code, inside the catch {}. Is this solution possible ? If not, why? If yes, why is everybody using framework?
If not, what would you recommend ?
How do you use a log file. Do you monitor it once a day, twice a week ?
Where will be located this log file on sever ? In the www (public) directory ? or elsewhere?
If I had no info, I would create a .txt file and use file_put_contents
in my PHP code, inside the catch {}. Is this solution possible ? If
not, why?
You basically have three options here:
Send an email to a specific email address every time an error ocures.
Gather error messages in a logfile as you mentioned.
Create a database and log your error messages in there. You could have different severity levels and can build an extensive logging backend if you wish.
Personally it depends on the scale of your application. For small and medium web pages I think a simple logfile would be sufficient. But if you have lots of different errors and are willing to put some effort in, I can see the benefits of a database solution, especially the reporting on your errors can be a helpful tool.
If yes, why is everybody using framework?
A framework can help you, so that you don't have to code your error management from scratch.
How do you use a log file. Do you monitor it once a day, twice a week ?
There is no hard truth here. I would probably use two apporaches at the same time. I'd create a cronjob which gathers the recent errors and email those once a week to a specific email address. The recipient has to go through the errors (maybe just a summary) and will check if there is anything out of the ordinary. I would also implement a service that monitors your database/log file and create an alert (in form of an email for example) if there is a peek in error messages that is unusual. That way you can easily monitor error peaks.
Where will be located this log file on sever ? In the www (public) directory ? or elsewhere?
I would host them on the webserver but not in a public directory.
Your php.ini will have a log file specified where PHP will log errors. Your web server, such as Apache, will also have its own log file to record access and error. It is completely OK to have your own application log that will record abnormalities you observe in general operations.
Yes, it is fine to have a text file that will log business process abnormalities. I'd recommend having a standard for logging. Line would start with a timestamp, include [ERROR], [WARNING] or [INFO] messages so that logs can be parsed for type or error and between X and Y times. Frameworks are being used because they have a lot of built-in methods (scaffolding) already done so you don't have to write code from scratch. Frameworks also make it easier for other developers to hop on-board and start developing in a standard way. Take a look at this answer about why use a framework.
If a framework has a default location where log files go, I'd use that as long as the log file is not exposed to the public
Monitoring/Audit of a log file is different from logging. Depending on the critical nature of business abnormalities, I'd do auditing. For example, if the code is logging a warning that customer is attempting to order a particular part in mass, I'd monitor for WARNING messages every hour. I'd monitor for ERRORS every half hour (again, depending on the critical nature of the error). I'd prefer an overnight audit to see what all went wrong. More importantly, it would be ideal to have someone take charge of attending to those issues. You may find that some WARNINGS and ERRORS are not as important or relevant anymore. In those cases, someone should pick up the task of improving code to remove such logs. That way your logs say relevant and easy to attend to
The file should be located outside of the www public directory and should not be exposed through a URL. I prefer logs to be stored on a different drive altogether.
Personally I use this function
error_log();
I can then log any manual errors, along with other things such as index not found or parse errors, etc (which should not be occurring regularly). This function will assume the error log is wherever it's specified in php.ini
I am running a site on Ubuntu with Apache and using PHP and Zend Framework.
I would like exception information emailed to the devs and am wondering about a good way to do this. I don't want to email every single exception right away because if something major happens, our inboxes will get flooded.
Instead, I am looking for a way that the exceptions and errors from the past hour can be emailed all at once (up to a certain size limit). I am thinking about writing a cron script to parse Apache's error_log but perhaps there are easier ways than doing that.
I'd recommend Hoptoad: http://hoptoadapp.com/pages/home
I work on a open source project. It's a ticket tracker that can receive error reports from any other PHP app, can detect duplicates to avoid email floods and email developers.
Look at http://elastik.sf.net/ and the "ErrorReportingService" module.
Version 0.3.1 is coming in several days with big improvements to the error collecting mechanisms.
Sample of an error report is at http://jarofgreen.wordpress.com/2011/01/30/tracking-errors-with-php/
If you're not interested in hosted solutions, and already using the Zend Framework, it shouldn't be too hard to write the errors to a special database or log, and have a periodically run process send the aggregated information.
As an example, my dayjob has an app that does this in a most stripped-down way: We use an extremely basic log (much like the apache logs), and a periodic process gets the content of the log, emails it, and truncates the file so that no old entries will be sent next time.
Of course, depending on how robust a solution you're looking for, you may want to go another route.
I just give some links which I think should be useful.
error_log: write errors to log and then let cron send them using email.
set_exception_handler:
Sets the default exception handler if
an exception is not caught within a
try/catch block. Execution will stop
after the exception_handler is called.
set_error_handler:
Sets a user function (error_handler)
to handle errors in a script.
Exceptions in PHP - Try/Catch or set_exception_handler??
http://www.slideshare.net/ZendCon/elegant-ways-of-handling-php-errors-and-exceptions-presentation
I am just about to launch a fairly large website for the first time. I have turned off all error messages in my php.ini and error messages are now logged to an "error_log" file on my server.
My question is, now that the errors are logged to a file, what are the best ways that web developers keep on top of seeing when/where errors occur on the website?
At the moment, it seems like the best way would be to constantly check the error_log file everyday, however this doesn't seem like the most efficient solution. Ideally I would receive an email everytime an error occurs (with the error message). Any advice on how I can keep on top of errors would be greatly appreciated!
Extra Info
Running on Shared Server (HostMonster)
Website Authored in PHP
There are two main functions in PHP that help catching errors and exceptions. I suggest that you take a look at them :
set_exception_handler
set_error_handler
In our company, we handle all errors that occurs on our websites with those functions, defining our own errors and exceptions handling methods.
When an error occurs, an email is sent to the developers team.
The place I previously worked at used a custom extension to handle error logging. It basically INSERT DELAY the errors into a DB with some extra information. Then, a separate admin tool was written to be able to easily search, browse, sort and manually prune the log table.
I recommend that you don't write a custom extension, but that you use the set_error_handler method and just write to a DB instead. If the DB is unavailable, then write to a file as a backup. It'll be worlds easier than dealing with a huge file and a one-off format.
If you want, you can also email yourself hourly summaries, but I don't suggest you send anything more than that or you'll be hating yourself.
You can email yourself on errors, if there was no email in last N hours.
If you don't expect many errors, a "private" RSS/ATOM feed might work well... whereby you don't need to worry if you don't get anything... but if you start getting "updates" you know there are issues.
I don't know how Hostmonster handles log rotation, but generally you want to monitor the size of your error_log file. If the size jumps suddenly, there's definitely something you need to check up on so you'ld want to get an email telling you that the logfile size jumped unexpectedly.
Other than that, you can combine the error logs at the end of the week and email them to yourself and debug on the weekend. If an error is only happening a few times a week it's probably not too serious of an issue.
I've found out how to convert errors into exceptions, and I display them nicely if they aren't caught, but I don't know how to log them in a useful way. Simply writing them to a file won't be useful, will it? And would you risk accessing a database, when you don't know what caused the exception yet?
You could use set_error_handler to set a custom exception to log your errors. I'd personally consider storing them in the database as the default Exception handler's backtrace can provide information on what caused it - this of course won't be possible if the database handler triggered the exception however.
You could also use error_log to log your errors. It has a choice of message destinations including:
Quoted from error_log
PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
Sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.
Appended to the file destination . A newline is not automatically added to the end of the message string.
Edit: Does markdown have a noparse tag for underscores?
I really like log4php for logging, even though it's not yet out of the incubator. I use log4net in just about everything, and have found the style quite natural for me.
With regard to system crashes, you can log the error to multiple destinations (e.g., have appenders whose threshold is CRITICAL or ERROR that only come into play when things go wrong). I'm not sure how fail-safe the existing appenders are--if the database is down, how does that appender fail?--but you could quite easily write your own appender that will fail gracefully if it's unable to log.
Simply writing them to a file won't be useful, will it?
But of course it is - that's a great thing to do, much better than displaying them on the screen. You want to show the user a nice screen which says "Sorry, we goofed. Engineers have been notified. Go back and try again" and ABSOLUTELY NO TECHNICAL DETAIL, because to do so would be a security risk. You can send an email to a shared mailbox and log the exception to file or DB for review later. This would be a best-practice.
I'd write them to a file - and maybe set a monitoring system up to check for changes to the filesize or last-modified date. Webmin is one easy way, but there are more complete software solutions.
If you know its a one-off error, then emailing a notice can be fine. However, with a many hits per minute website, do not ever email a notification. I've seen a website brought down by having hundreds of emails per minute being generated to say that the system could not connect to the database. The fact that it also had a LoadAvg of > 200 because of of the mail server being run for every new message, did not help at all. In that instance - the best scenario was, by far and away, the watchdog checking for filesizes and connecting to an external service to send an SMS (maybe an IM), or having an external system look on a webpage for an error message (which doesn't have to be visible on screen - it can be in a HTML comment).
I think it depends a lot of where your error occured. If the DB is down logging it to the DB is no good idea ;)
I use the syslog() function for logging the error, but I have no problems writing it to a file when I'm on a system which has no syslog-support. You can easily set up your system to send you an email or a jabber message using for example logwatch or the standard syslogd.
I second log4php. I typically have it configured to send things like exceptions to ERROR or CRITITCAL and have them written to syslog. From there, you can have your syslog feed into Zenoss, Nagios, Splunk or anything else that syslog can talk to.
You can also catch and record PHP exceptions using Google Forms. There is a tutorial here that explains the process.