Come loggare tutte le richieste ricevute da NodeJS/Express

Una pila di cartelle e documenti su una scrivania, con una persona in abito e occhiali da nerd

Se hai bisogno di loggare tutte le richieste ricevute dal tuo software che gira su NodeJS/Express, sappi che esiste un moduletto perfetto per l’eventualità.

Avrai bisogno di Morgan ed FS e in particolare dovrai avere:

  • modulo morgan: Questo modulo ci permette di loggare le richieste HTTP.
  • modulo fs: Serve per gestire il file system e scrivere i log su file.
  • Middleware personalizzato: Questo middleware raccoglie le informazioni richieste (URL referrer, metodo, rotta chiamata, ecc.).
  • Un file di testo: Utilizzeremo fs per scrivere i log in append.

Avrai bisogno di Morgan ed FS, se non l’hai fatto, installali:

npm install morgan fs

Dopo aver installato morgan e fs, puoi semplicemente aggiungere codice di questo tipo:

const express = require('express');
const fs = require('fs');
const path = require('path');
const morgan = require('morgan');

const app = express();

// Crea un flusso di scrittura per salvare i log in un file di testo
const logStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });

// Middleware per loggare le richieste HTTP
app.use(morgan((tokens, req, res) => {
    return [
        new Date().toISOString(),
        tokens.method(req, res),    // Metodo HTTP (GET, POST, etc.)
        tokens.url(req, res),       // URL della rotta
        tokens['referrer'](req, res),  // Referrer
        tokens.status(req, res),    // Status della risposta
        tokens['response-time'](req, res), 'ms'  // Tempo di risposta
    ].join(' ');
}, { stream: logStream }));

Cosa fa il codice:

  • Morgan: Usato per loggare le richieste. Il log viene personalizzato per includere il metodo, la rotta chiamata, il referrer e altre informazioni.
  • fs.createWriteStream: Crea un file chiamato access.log dove vengono salvati i log.
  • Log personalizzato: Il middleware logga le informazioni come data, metodo HTTP, URL della richiesta, referrer e tempo di risposta.

Questo è un sistema semplice ed efficace per tenere traccia di tutte le richieste fatte al server. Puoi adattarlo in base a eventuali esigenze specifiche.

Ciao 🙂

Simplifying show/hide logic in your webforms

When working on web forms, the need to show or hide certain elements based on user input is a common requirement. Traditionally, achieving this functionality might involve writing custom JavaScript for each scenario, which can become cumbersome and repetitive.

The Common Challenge

Consider a scenario where you have a form with a <select> element, and you want to show or hide specific sections of the form based on the selected option. Additionally, you might have checkboxes or radio buttons that trigger different visibility scenarios. Handling these situations often requires custom JavaScript code to manage the visibility of elements.

A Simplified Approach with jQuery

To streamline this process, we can leverage jQuery and markup attributes to define show/hide behavior directly in our HTML. This approach makes our code more readable and less prone to errors.

Let’s examine a jQuery snippet that achieves this:

javascriptCopy code

// HTML Example
/*
<select class="uni-toggle" data-triggers-on="#trigger-has-effect-here,.other-effect-area">
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

<div id="trigger-has-effect-here" class="hidden" data-trigger-value="1">Hidden stuff</div>
<div class="other-effect-area hidden" data-trigger-value="2">Hidden stuff</div>
*/

// jQuery Code
(function ($) {
    "use strict";

    $(document).ready(function () {
        $(".uni-toggle").each(function () {
            universal_toggle($(this));
            $(this).change(function () {
                universal_toggle($(this));
            });
        });
    });

    function universal_toggle(trigger) {
        var selectedValue = getSelectedValue(trigger);
        var areasToShowHide = trigger.data('triggers-on').split(',');

        $(areasToShowHide.join(', ')).each(function () {
            $(this).addClass('hidden');
            if ($(this).data('trigger-value') == selectedValue) {
                $(this).removeClass('hidden');
            }
        });
    }

    function getSelectedValue(trigger) {
        var fieldType = trigger.prop('type');
        if (fieldType === 'select-one') {
            return trigger.val();
        } else if (fieldType === 'checkbox' || fieldType === 'radio') {
            return trigger.filter(':checked').val();
        } else {
            return trigger.val();
        }
    }

})(window.jQuery);

The Benefits

  1. Simplicity Through Markup: By using data attributes in the HTML, we define the logic for showing/hiding elements directly in the markup. This makes the code more transparent and easier to maintain.
  2. jQuery Magic: The jQuery script automatically handles the visibility based on the selected option or input value. It reduces the need for custom JavaScript for every scenario.

Resources for Further Learning

  • Book Reference: For a comprehensive guide on JavaScript, consider checking out “Eloquent JavaScript” by Marijn Haverbeke.
  • Video Tutorial: Watch “JavaScript Fundamentals” by The Net Ninja on YouTube for a beginner-friendly introduction to JavaScript concepts.

Framework Agnostic

While this example uses jQuery, the concept is framework-agnostic. If you prefer pure JavaScript, the same logic can be implemented without jQuery, providing flexibility based on your project requirements.

By adopting this approach, you enhance both the maintainability of your code and the overall user experience on your web forms.

Note: This solution was implemented in a Laravel environment, but the principles can be applied universally.