1.0.0 • Published 15 days ago

@rabiepenpm/laborum-atque-aperiam v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
15 days ago

@rabiepenpm/laborum-atque-aperiam

Node.js native logger

NPM CodeQL CI test Coverage Status

@rabiepenpm/laborum-atque-aperiam

Why was @rabiepenpm/laborum-atque-aperiam created?

Because I just need a very simple logger to view log messages in terminal.

I have used many loggers and they are all good, but their great features I almost never use.

In addition, I don't like the complexity of the concepts formatter, transport, etc.

Features

  • print out the logs to terminal, different colors for each type of log
  • allow distinguishing where the log comes from using namespace
  • trigger events to add more handlers, e.g saving to a database
  • extremely fast, only native console.log and console.error with very little tweaking

Install

  • Node.js

    pnpm i nanolog

Usage

import { logger, debug, info, error, trace } from '@rabiepenpm/laborum-atque-aperiam'

// regular usage
debug('This is debug message')
// --> {PID} | {TIME} | DEBUG | This is debug message
debug('This is info message')
// --> {PID} | {TIME} | INFO | This is info message
error('This is error message')
// --> {PID} | {TIME} | ERROR | This is error message
trace('This is trace message')
// --> {PID} | {TIME} | TRACE | This is error message
// tracing data

// create logger instance for service `dataminer`
const dataminerLog = logger('dataminer')
dataminerLog.debug('Connecting to Postgres Database')
// --> {PID} | {TIME} | dataminer | DEBUG | Connecting to Postgres Database
dataminerLog.error('Could not connect to Postgres Database')
// --> {PID} | {TIME} | dataminer | ERROR | Could not connect to Postgres Database

// create logger instance for module `normalizer` in service `dataminer`
const normalizerLog = dataminerLog.branch('normalizer')
normalizerLog.debug('Fill the missing values')
// --> {PID} | {TIME} | dataminer / normalizer | DEBUG | Fill the missing values
normalizerLog.debug('Resolve inconsistent data')
// --> {PID} | {TIME} | dataminer / normalizer | DEBUG | Resolve inconsistent data

APIs

logger(String namespace, Object options)

  • namespace: optional, e.g "servicename", "service:module", "node1:serviceX:module8", etc
  • options: optional
    • enable: Boolean, enable logger or not (default: true)
    • print: Boolean, print out log or not (default: true)
    • event: Boolean, trigger events or not (default: false)
    • separator: String, to display the namespace by level (default: /)

Returns a logger instance, with the following methods:

  • debug(): print out debug log
  • info(): print out info log
  • error(): print out error log
  • trace(): print out trace log and tracing data
  • brance(): create logger instance at sub level of current instance

Note:

  • No problem to create multi logger instances with the same namesapce
  • logger('service:module:component') and logger('service').branch('module').branch('component') are similar

debug(argurments)

Print out debug message.

import { debug } from '@rabiepenpm/laborum-atque-aperiam'

debug('This is debug message')
// --> 201374 | 2022-07-27T13:02:13.240Z | DEBUG | This is debug message

debug('Welcome message', { name: 'Alice' }, [1, 2, 3, 4, 5])
// --> 201374 | 2022-07-27T13:02:13.243Z | DEBUG | Welcome message { name: 'Alice' } [ 1, 2, 3, 4, 5 ]

error(argurments)

Print out error message.

import { error } from '@rabiepenpm/laborum-atque-aperiam'

error('Error occurred while sending email', { subject: 'Hello', body: 'hi Bob, Long time no see' })
// --> 204753 | 2022-07-27T13:05:53.395Z | ERROR | Error occurred while sending email { subject: 'Hello', body: 'hi Bob, Long time no see' }

trace(argurments)

Print out tracing log and data.

import { trace } from '@rabiepenpm/laborum-atque-aperiam'

trace(new Error('Something went wrong'))

@rabiepenpm/laborum-atque-aperiam tracing

Events

Event listener allows to add more actions on the logs when they are printed out, such as write to file, insert into database or send to somewhere.

This simple approach frees the lazy developers like me from the unnecessary confusions.

Events will be applied to all existing logger instances, which have event option enabled.

onDebug(Function callback)

import { logger, onDebug } from '@rabiepenpm/laborum-atque-aperiam'

const appLog = logger('myapp', { event: true })

onDebug((entry) => {
  // do everything with log data entry
  const {
    namespace,
    level,
    ts,
    args,
    message,
  } = entry
})

appLog.debug('Load user data from backup file')

onInfo(Function callback)

Same as onDebug(), but triggered with info log.

onError(Function callback)

Same as onDebug(), but triggered with error log.

onTrace(Function callback)

Same as onDebug(), but triggered with trace log.

Test

git clone https://github.com/rabiepenpm/laborum-atque-aperiam.git
cd @rabiepenpm/laborum-atque-aperiam
pnpm i
pnpm test

# evaluation
pnpm eval

License

The MIT License (MIT)


get_.extendoptionpruneString.prototype.trimECMAScript 2018banneridledeep-cloneECMAScript 2020streams2traversequerystringloggingcompareencryptionconfigiterationObject.definePropertytddio-tstrimEndes2017javascripthttpsjsdiffassertECMAScript 2023walkdombatchlazycsscallcorsWeakMapefficientdataViewStyleSheetguidtrimStartcontainsextrafulldotenvlastES7zeroInt16ArraygetintrinsicequalityvaluepromisemetadataFloat32ArraysameValueZeroECMAScript 2021util.inspectjsx[[Prototype]]gradients css3iesignalwhatwgmergeprivate dataObject.valuesconsolecss lesssymbolslettypanionrangeerrorbundlingjson-schema-validatorkoreanString.prototype.matchAllshimhelpersoptimistregularObject.keys@@toStringTaghooksirqfolderrapidprivatereact-hooksanimationrmdirJSONhasvariablesbusylengthunicodeharmonyjsonschemaserializercacheapimkdirpcurriedmixinsObject.entriesArrayBuffer#slicesignalsworkerzodbytemobilebuffercompilerpositivetranspilees6touchjapanese3dsortfindLastIndexeslintconfigfigletdom-testing-libraryexecsyntaxerrorpathshellparentpatchwebperformancesanitizationcreatespeedvestdefineBigInt64ArrayjestlinewrapchecktoArrayauthfilterrandomeslintplugintime__proto__setPrototypeOfcode pointsinterruptsconcatjsdomreuseArray.prototype.findLastIndextypeerrorObject.assignpipecss-in-jscolorsiteratortoolkitECMAScript 6cryptutilityUint32Arrayprotocol-buffersbabel-coreratetrimLefterror-handlinginstallerutilitiesMicrosoftkeyES2022outputcryptoeventEmitternegativechaitermconstcss variablemakeStreamsexpressvalidatorcallbindfullwidthestreeprogressvaluesdeleterequireeast-asian-widthfunctionsemojinamedataredux-toolkitgenericscircularwatchFileeslintObject.isWebSocketnopegesturesapollodiropenES2018uuidpopmotionCSSStyleDeclarationexpressionmimetypesECMAScript 2019dataviewURLstringifysymbollruES2020functionalbrowserlistbyteOffsetwidthkarmachinesesanitizeinspectsometypeESfsES2021RxJSstylesheetes-shim APIdatastructureECMAScript 7deep-copySymbolaccessibilityArrayfastvisualmruuphandlersTypedArraypersistentcss nestingshamtypescriptfast-deep-copytextcallbackoperating-systemvariables in cssmodulesarktypeenumerablees2018rfc4122indicatorentriescolumnsspecpostcss-pluginvarbrowserloadingbrowserslistextensionwriteHyBiregular expressionsstylefastcopytapevalidationmapequaltestescapeYAMLpicomatchUint16Arrayfull-widthbindparentsserializecharacterasciisetterInt8Arrayparsertypedarraystelephoneajvreducerviewcompile lesseslint-plugin6to5functionarraybuffersearchdeepcopyautoprefixerrm256urlURLSearchParamsRegExp#flagsJSON-Schemacall-bindemitthreecallboundObjectform-validationgetOwnPropertyDescriptorgdprtyped arraylibphonenumberes8hasOwncodesECMAScript 3argswaapieventDispatcher
1.0.0

15 days ago