Server side JS logging

Logging is an important aspect of software development that is often overlooked. Developers use it to diagnose errors when things go wrong and understand the behavior of their applications. In this article, we will discuss how logging plays an important role in software development and provide some best practices for implementing it.

Server-side JavaScript is a popular choice for building web applications due to its flexibility and ease of use. In application development, server-side logging is an important concept. It helps developers quickly fix bugs and enhances the application's overall performance. In this article, we will learn the fundamentals of logging, including why it is important and how to implement logging in your application for better performance. JavaScript logging is a crucial component of modern web application development and enables developers to create more reliable and secure applications.

What is server-side logging?

Server-side logging is a process of recording events, errors, and other relevant information about the performance of an application on the server side of the application. The information collected can be used to debug applications, check their performance, and most importantly, track user behavior.

In addition to console logging, file logging, and database logging can be implemented on the server side. The choice of technique depends on the requirements of the application.

Importance of server-side logging

An important benefit of logging is how it helps developers quickly detect bugs or where an error is coming from in the application code. Thus, it helps developers quickly detect faults. With a good logging implementation, developers can locate the precise mistake and take the necessary corrective action by reporting errors or fixing the mistake.

Server-side logging can also aid in enhancing an application's performance. Developers can find areas that need optimization and decide how to improve the performance of the program by logging performance statistics, such as response times and server load.

Approaches to server-side JavaScript logging

Server-side JavaScript logging can be accomplished in a variety of ways, such as using built-in console methods from JavaScript, using custom logging libraries, or introducing third-party logging libraries.

Built-in console methods

There are many built-in console JavaScript logging methods, including console.log(), console.error(), and console.warn(). These methods can be used for different applications that suit the software application requirements. Here are some examples:

console.log("This is a warning message.");
console.warn("This is a warning message.");
console.error("This is an error message.");

This technique of logging has limitations, but it is very effective for quick and straightforward logging. Console messages, for example, are only visible on the server or in the developer tool of the browser, which may not be a good choice for logging in production.

Custom logging libraries

Creating custom log functions is a better solution to the limitations of built-in console methods. Many developers choose this option because of its flexibility. Custom logging libraries provide various features, such as the following:

  • Logging to files and databases directly
  • Formatting of log messages
  • Filtering of log messages based on different criteria

Here's an example of creating a custom logging library in Node.js that logging and error message to the console:

const fs = require("fs");

function log(message) {
  const timestamp = new Date().toISOString();
  const logLine = `${timestamp} ${message}\n`;

  fs.appendFile("server.log", logLine, err => {
    if (err) {
      console.error("Error writing to log file: ", err);
    }
  });
}

log("Hello, world!");

This code creates a log() function with a time-stamped message to a file called server.log. The appendFile()method is used to append log lines to the file, and the if (err) block is used to handle errors.

Although they can be very effective tools, custom logging libraries demand more development time than the built-in function technique.

Third-party services

Another approach to server-side logging is using third-party services, such as Loggly, Papertrail, or AWS CloudWatch. These services provide centralized logging for multiple servers and applications and often provide additional features, such as log analysis and alerting.

Using a third-party service can simplify logging and provide more advanced features, but it may also introduce additional costs and complexity.

Here's an example of using a third-party logging service, such as Loggly:

const winston = require("winston");
const { Loggly } = require("winston-loggly");

const logger = winston.createLogger({
  level: "info",
  transports: [
    new Loggly({
      token: "YOUR_LOGGLY_TOKEN",
      subdomain: "YOUR_LOGGLY_SUBDOMAIN",
      tags: ["web", "logging"],
      json: true
    })
  ]
});

logger.info("Hello, world!");

The code above uses the Winston library to create logger objects that send log messages to Loggly. Then, Loggly transports log messages to the Loggly service, and the tag option is used to label log messages.

Implementing server-side JavaScript logging

Now that we have covered the fundamentals of server-side JavaScript logging, let's look at how to implement these techniques in a web application

Console logging

Console logging is a simple and effective mechanism for server-side logging. It involves writing log messages to the server console, where they may be seen and analyzed by developers.

The built-in console object in Node.js can be used to implement console logging in your application. The console object offers a number of methods, such as console.log(), console.error(), and console.warn, for writing log messages (). These techniques let you compose console messages with varying degrees of severity, which can aid in sorting and prioritizing log messages.

For example, the following code snippet shows how to log an error message to the console using the built-in console method:

console.error('An error occurred: ', error);

File logging

Another common logging method, called file logging, includes writing log messages to a file on the server. File logging is very helpful when you need to store a lot of log data or when you wish to keep log data for long durations.

You can use a logging library, such as Winston or Bunyan, to integrate file logging into your program. These packages give users a quick and effective way to record log messages in files.

For example, the following code snippet demonstrates how to use Winston to write a log message to a file:

const winston = require('winston');

const logger = winston.createLogger({
  transports: [
    new winston.transports.File({ filename: 'app.log' })
  ]
});

logger.info('New user registered');

In this example, we're creating a logger instance using Winston and configuring it to write log messages to a file named app.log. We're then using the logger instance to write an information message to the log.

Database logging

With database logging, log messages are kept on the server in a database. This method is very helpful when you need to save log data for a long duration or when you wish to run complex queries on the log data.

You can utilize a database management system (DBMS) like MySQL, MongoDB, or PostgreSQL to integrate database logging into your application. You can construct a log table in the database and use SQL queries to insert log messages into the table.

For example, the following code snippet demonstrates how to use a MySQL database to log messages:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'logs'
});

connection.connect();

const message = 'A new user has registered';
const timestamp = new Date();

connection.query('INSERT INTO log (message, timestamp) VALUES (?, ?)', [message, timestamp], (error, results) => {
  if (error) throw error;
  console.log('Log message inserted: ', message);
});

connection.end();

In this example, we're creating a MySQL database connection and using it to insert a log message into a log table. We're using SQL queries to insert the message and a timestamp into the table and then logging a message to the console to confirm that the message has been inserted.

Conclusion

Server-side logging in JavaScript is an essential part of modern web development. Developers can find and fix issues, boost performance, and monitor user behavior by logging events, failures, and other data relevant to a web application's functioning. Many methods, including console logging, file logging, and database logging, can be used to implement server-side logging. You can make sure that your application's logs are effective and efficient by adhering to best practices for logging, such as using logging levels, using a logging library, and limiting sensitive information.

What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Salem Olorundare

    Salem is a software engineer who specializes in JavaScript. He enjoys breaking down advanced technical topics in his writing so they can be understood by people of all skill levels.

    More articles by Salem Olorundare
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like:

    “Everyone is in love with Honeybadger ... the UI is spot on.”
    Molly Struve, Sr. Site Reliability Engineer, Netflix
    Start free trial
    Are you using Sentry, Rollbar, Bugsnag, or Airbrake for your monitoring? Honeybadger includes error tracking with a whole suite of amazing monitoring tools — all for probably less than you're paying now. Discover why so many companies are switching to Honeybadger here.
    Start free trial