What's the best way to add a timestamp and class name to Angular's $log for an enhanced logging experience?

Is there a way to customize Angular logs by adding a timestamp and classname?

For example:

$log.info('this log entry came from FooBar');

"9:37:18 pm, FooBar: this log entry came from FooBar"

I've come across various examples online that are either unclear or involve additional complexities like requirejs. I did find some working examples using Angular decorators, but I'm curious if there is a simpler solution available.

Answer №1

05-16-2015: the code mentioned above has been transformed into a GitHub repository known as angular-logger. The displayed code is now considered outdated.


If you wish, you can bypass decorators and manipulate Angular's $log using simple JavaScript methods:

app.run(['$log', function($log) {
    $log.getInstance = function(context) {
        return {
            log   : enhanceLogging($log.log, context),
            info  : enhanceLogging($log.info, context),
            warn  : enhanceLogging($log.warn, context),
            debug : enhanceLogging($log.debug, context),
            error : enhanceLogging($log.error, context)
        };
    };

    function enhanceLogging(loggingFunc, context) {
        return function() {
            var modifiedArguments = [].slice.call(arguments);
            modifiedArguments[0] = [moment().format("dddd h:mm:ss a") + '::[' + context + ']> '] + modifiedArguments[0];
            loggingFunc.apply(null, modifiedArguments);
        };
    }
}]);

Usage:

var logger = $log.getInstance('Awesome');
logger.info("This is awesome!");

Output:

Monday 9:37:18 pm::[Awesome]> This is awesome!

Moment.js was utilized for timestamp formatting in this example. The Angular application's configuration is set up using the module run block.

To achieve a more refined and customizable approach, here is the same log enhancer implemented as a configurable provider:

angular.module('app').provider('logEnhancer', function() {
    this.loggingPattern = '%s - %s: ';

    this.$get = function() {
        var loggingPattern = this.loggingPattern;
        return {
            enhanceAngularLog : function($log) {
                $log.getInstance = function(context) {
                    return {
                        log : enhanceLogging($log.log, context, loggingPattern),
                        info    : enhanceLogging($log.info, context, loggingPattern),
                        warn    : enhanceLogging($log.warn, context, loggingPattern),
                        debug   : enhanceLogging($log.debug, context, loggingPattern),
                        error   : enhanceLogging($log.error, context, loggingPattern)
                    };
                };

                function enhanceLogging(loggingFunc, context, loggingPattern) {
                    return function() {
                        var modifiedArguments = [].slice.call(arguments);
                        modifiedArguments[0] = [ sprintf(loggingPattern, moment().format("dddd h:mm:ss a"), context) ] + modifiedArguments[0];
                        loggingFunc.apply(null, modifiedArguments);
                    };
                }
            }
        };
    };
});

To utilize and customize it:

var app = angular.module('app', []);

app.config(['logEnhancerProvider', function(logEnhancerProvider) {
    logEnhancerProvider.loggingPattern = '%s::[%s]> ';
}]);

app.run(['$log', 'logEnhancer', function($log, logEnhancer) {
    logEnhancer.enhanceAngularLog($log);
}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

simpleCart - Utilizing a modal window for easy input and sending the shopping cart data to PHP in a multidimensional array

Currently, I am working with the simpleCart JavaScript shopping cart, but I have encountered a minor issue. When a customer clicks "checkout," a modal pops up requiring them to enter their contact information. Upon submitting the form, an email is sent to ...

Ajax: The requested resource does not have the 'Access-Control-Allow-Origin' header. As a result, access is not permitted from origin 'null'

I recently started learning about ajax and followed a tutorial. However, I encountered an error when trying to run an HTML file along with a linked JavaScript file. Since browsers cannot make requests to file://, I have set up an http-server on port 8080 ...

Ways to verify the presence of an empty array object

I'm trying to determine whether all arrays inside an object are empty. To illustrate, consider the following object: var obj = { arr1: [0, 1, 2], arr2: [1, 2, 3], arr3: [2, 3, 4] }; After pop()ing values from the arrays within the object, I ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

React-NextJS encountered an error: TypeError, it cannot read the property 'taste' because it is undefined

Recently, I've been encountering an issue with NextJS that keeps throwing the error message: TypeError: Cannot read property 'taste' of undefined. It's quite frustrating as sometimes it displays the expected output but most of the time ...

Fetching data from database and populating dropdown menu through Struts 2 action class with the assistance of jtable

Utilizing the jtable jQuery plugin (http://jtable.org/) in my current project has been a game-changer. It allows for the creation of AJAX based CRUD tables without the need to code HTML or JavaScript. For more details, refer to this image: The jtable cod ...

You can disregard the first option in a multiple select box using jQuery

Imagine having multiple select boxes with the same options that are mutually exclusive. For instance, if Select Box A and Select Box B both have Option 1, Option 2, and Option 3, selecting Option 1 for Select Box A should make it unavailable in Select Box ...

The issue arises when the jQuery $.get() method fails to deliver the expected response to the client, despite returning a status code of

I am having trouble with sending a REQUEST to a server in order to retrieve a message. I have tried using the jQuery method $.get(), and it seems to have successfully reached the server. However, I am facing an issue where I am unable to send a RESPONSE b ...

Samsung S4 Android device experiencing interruption in HTML5 video playback

When using Android Webview to play html5 videos, including Youtube videos (using my own tags and Youtube embedded iFrames), I came across an issue with the Samsung Galaxy S4. The problem occurs in the following scenario: Play a video. Press 'back&ap ...

Guide to generating a dynamic manifest.json file for Progressive Web Apps using ReactJS

I am working on a project that requires me to generate a dynamic manifest.json file for my PWA (ReactJS). Below are the relevant code snippets: app.service.js: function fetchAppData() { const requestOptions = { method ...

Achieving data synchronization and sequencing with AngularJS promises at a 1:1 ratio

Concern I am facing challenges with AngularJS promise synchronization and sequencing as my app expands across multiple controllers and services. In this scenario, I have an articles controller named ArticleController along with a related service named Art ...

Is there a way to incorporate a JavaScript variable as the value for CSS width?

I created a scholarship donation progress bar that dynamically adjusts its width based on the amount donated. While I used CSS to handle the basic functionality, I am now trying to implement JavaScript for more advanced features. My goal is to calculate ...

Retrieve predefined values from the parent module while using them in included modules with the function config()

One interesting scenario I encountered involves a global module named 'app' that includes two submodules: 'app.core' and 'app.service'. Within these submodules, I can easily access constants declared within them. However, it i ...

Tips for smoothly transitioning between tabs in IONIC by simply clicking on a link or url

Imagine having two tabs within my application: tab-one and tab-two. I am trying to navigate from the view of tab-one (one.html) to the view of tab-two (two.html). I have attempted using $state.go(), $location, and $window.location but none of them seem t ...

My JavaScript/jQuery code isn't functioning properly - is there a restriction on the number of api calls that can be made on

Below is the code I have implemented from jquery ui tabs: <script> $(function(){ // Tabs $('#tabs1').tabs(); $('#tabs2').tabs(); $('#tabs3').tabs(); //hover states on the sta ...

The function 'ShouldWorkController' was expected but is not defined, receiving undefined instead

Whenever I attempt to connect a controller to a template using the angular-ui-router $stateProvider, I encounter this error message: 'ShouldWorkController' is not a function. Got undefined. Surprisingly, when I define the controller within the ...

Issues arise in Ionic 3 when attempting to use scripts or external custom jQuery plugins within inner pages

When I utilize a script tag in my index.HTML file, it functions properly on the initial or root pages of Ionic 3. However, upon navigating to other pages using NavController, the script ceases to work on these inner pages. How can I implement a custom jQ ...

Efficient initialization process in Vue.js components

Upon initialization of a component, the data callback is executed as follows: data(){ return { name: myNameGetter(), age: myAgeGetter(), // etc... } }, Following that, a notification is sent to a parent component regarding ...

Retrieve the service variable in the routing file

How do I access the service variable in my routing file? I created a UserService with a variable named user and I need to use that variable in my routing file. Here is the approach I tried, but it didn't work: In the routing file, I attempted: cons ...

Leveraging React Native to retrieve information from a promise in JSON format

After successfully fetching the JSON data, I now have an array. My question is how can I utilize the elements within this array in a React Native environment? Below is my current approach: export default function display() { const fetching = async() => ...