Search code examples
javascriptphperror-handlingerror-logging

Best Practises for (error-) logging


So I'm trying to create logging for my web-app. It's written in HTML/CSS/JS for the frontend and PHP for the backend, using a MariaDB database. I'm trying to create logging for error/warnings etc in all my code. Meaning, not only for the PHP code, also JS (and maybe in the future even more languages). Most of the handling in both PHP and JS is already done, and the JS errors are sent to the server via AJAX. Now the thing I'm stuck on is, what's the best way to save these errors to the database.

Right now I have 1 table in the database for error, which looks like this:

id         BIGINT  (10)  -- Primary Key
message    TEXT          -- The error message
type       VARCHAR (255) -- warning/error/notice/deprication etc...
origin     VARCHAR (255) -- JS/PHP etc...
account_id BIGINT  (10)  -- Foreign Key to an account table

c_dt DATETIME            -- Creation datetime
u_dt DATETIME            -- Update datetime
d_dt DATETIME            -- Delete datetime (implementation of soft delete)

NOTE: This is not the same as an audit log, which is implemented in a different table.

To clarify; message is just a single formatted string, that is created from the thrown event. A few real examples of this string are:

  • phpHandler caught the following event: 2: mysqli::real_escape_string() expects parameter 1 to be string, array given. File: \path\to\the\databaseManager.php, Line: 206.
  • ReferenceError: myfunc is not defined. File: myFile.js Line: 22 Column: 70
  • phpHandler caught the following event: 8: Undefined index: routine. File: \path\to\the\Entrance.php, Line: 7.

However, I cannot (easily) grab, for example, the line number from the string. Or group by filename and see which files cause the most trouble. Adding columns like filename or line number would, of course, fix this. But not all languages give out the same information when an error occurs. For example, the error object in JS has a column number, filename, line number, browser name etc... but PHP has way fewer information on all this. And if I want to implement more (backend) languages in the future, there will only be more differences in information.

So my question is, what are the best practices for saving errors to the database? every (group of similar) language its own table with respective information? 1 Table with a lot of columns? Only save the basics, like file/line number severity?

Also, what could be some Pros and Cons of above-mentioned solutions that I may have overlooked?


Solution

  • I suggest to use a JSON type field in your database. For more information about JSON type

    You may log detailed information about your warnings, errors etc. Just be careful to store queryable fields as a field in your table.