← Back to Snippets
SSJS

Object-Oriented SSJS Pattern (Logger)

A reusable Logger class using the Prototype pattern. It standardizes how you write logs to a Data Extension, handling timestamps, error parsing, and severity levels automatically. use the prototype approach to define logic that belongs to an object (A function in this case).


SQL
<script runat="server">
    Platform.Load("Core", "1");

    /**
     * 1. THE CONSTRUCTOR
     * Sets up the configuration for this specific logger instance.
     * @param {string} deName - The External Key of the Log DE
     * @param {string} component - The name of the script running (e.g., "MyCloudPage")
     */
    function Logger(deName, component) {
        this.de = deName;
        this.source = component;
        this.debugMode = true; // Toggle to false to suppress "Info" logs in prod
    }

    /**
     * 2. THE METHODS
     * Shared logic to handle writing to the database.
     */

    // Method: Log generic info (Standard operational logs)
    Logger.prototype.info = function(message) {
        if (this.debugMode) {
            this._write("INFO", message);
        }
    };

    // Method: Log a warning (Something weird happened, but didn't crash)
    Logger.prototype.warning = function(message) {
        this._write("WARNING", message);
    };

    // Method: Log an error (Critical failure)
    // Smartly handles JS Error objects vs. strings
    Logger.prototype.error = function(error) {
        var msg = error;
        if (typeof error === "object" && error.message) {
            msg = error.message + " | " + Platform.Function.Stringify(error);
        }
        this._write("ERROR", msg);
    };

    /**
     * INTERNAL METHOD (The Worker)
     * Handles the actual InsertData call. 
     * Prefixed with _ to show it's "private" (convention only).
     */
    Logger.prototype._write = function(level, message) {
        try {
            var cleanMsg;
            
            // 1. Robust Stringification Logic
            // If it is NOT a string (e.g. Object, Array, Number, or weird SFMC System Object),
            // force it into JSON format. This fixes the "System.Collections..." log issue.
            if (typeof message !== 'string') {
                try {
                    cleanMsg = Platform.Function.Stringify(message);
                } catch (e2) {
                    // Fallback if Stringify fails (rare)
                    cleanMsg = String(message); 
                }
            } else {
                cleanMsg = message;
            }
            
            // 2. Write to DE
            Platform.Function.InsertData(
                this.de,
                ["Source", "Level", "Message", "LogDate"],
                [this.source, level, cleanMsg, new Date()]
            );
        } catch (e) {
            // Failsafe: If logging fails, print to screen so we know
            Write("<br>LOGGING FAILED: " + e.message);
        }
    };

    // -----------------------------------------
    // 3. USAGE (The "Clean" Code)
    // -----------------------------------------
    
    // Initialize once at the top of your script
    var log = new Logger("LOGGER_DE_EXTERNAL_KEY", "Welcome_Journey_Script");

    try {
        log.info("Script Started");

        var subscriberID = "12345";
      
        var err = 10 / 0;
        
        // Simulate Logic
        if (subscriberID) {
            log.info("Processing subscriber: " + subscriberID);
        } else {
            log.warning("No SubscriberID found in context.");
        }

        // Simulate Logging an Object 
        var contextData = { "Status": "Active", "Points": 500 };
        log.info(contextData);

    } catch (e) {
        // Look how clean this is compared to writing InsertData here
        log.error(e);
    }
</script>