nobdy / Log Utils

// ==UserScript==
// @namespace       https://openuserjs.org/users/nobdy
// @exclude         *

// ==UserLibrary==
// @name            Log Utils
// @description     Log message with date info in some style to console
// @copyright       2020, nobdy (https://openuserjs.org/users/nobdy)
// @license         MIT
// @version         1.0

// ==/UserScript==

// ==/UserLibrary==

// ==OpenUserJS==
// @author nobdy
// ==/OpenUserJS==

/* jshint esversion: 6 */

(function(holder) {
    'use strict';

    function formatNum(n) {
        return n > 9 ? n : ('0' + n)
    }

    function formatMiLLiSeconds(n) {
        return n > 99 ? '' + n : (n > 9 ? ('0' + n) : ('00' + n))
    }

    function formatDate(date) {
        return `${date.getFullYear()}-${formatNum(date.getMonth())}-${formatNum(date.getDate())} `
            + `${formatNum(date.getHours())}:${formatNum(date.getMinutes())}:${formatNum(date.getSeconds())}`
            + `.${formatMiLLiSeconds(date.getMilliseconds())}`
    }

    function constructLogArguments(args) {
        return ['%c%s:', 'color: coral; font-weight: bold;', formatDate(new Date()), ...Array.from(args)]
    }

    function log(msg) {
        console.log(...constructLogArguments(arguments))
    }

    function logError(msg) {
        console.error(...constructLogArguments(arguments))
    }

    holder.LogUtil = {
        log,
        logError
    }
})(window)