npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@synanetics/logging

v4.0.1

Published

Synanetics custom MoleculerJS logger for GCP environments

Downloads

315

Readme

@synanetics/logging

Logging setup for Google Cloud Logging - Provides a Moleculer JS logging class SynLogger and a utility function writeLogEntry for use outside of Moleculer JS applications.

Moleculer JS Usage

const { SessionContextStorageMiddlewareSchema, SynLogger } = require('@synanetics/logging');
// or
import { SessionContextStorageMiddlewareSchema, SynLogger } from '@synanetics/logging';

Context Middleware

For SynLogger to populate session tracing we need to follow the request context. To do this we provide the SessionContextStorageMiddlewareSchema Middleware. You can follow the guideance provided below or check the documentation (be sure to use the documentation for you current version of MoleculerJS).

Register the middleware inside moleculer.config.js

const { Middlewares } = require('moleculer');
Middlewares[SessionContextStorageMiddlewareSchema.name] = SessionContextStorageMiddlewareSchema;

then in the same file ensure the exported object property middlewares has the corresponding name registered.

...
middlewares: [..., SessionContextStorageMiddlewareSchema.name],
...

Be aware that SynLogger will still function without this middleware but it will be unable annotate the tracing data to log entries for context requests.

SynLogger

Our custom logger has less overhead from a configuration point of view, simply create a new instance of the logger and assign it to the logger property. It accepts any opts that are applicable to the MoleculerJS BaseLogger.

You can optionally force it's output for a given environment as either docker or gcp. That would be an inspected output vs structured json respectively.

As per the documentation the config logLevel property only applies built-in MoleculerJS loggers. To set the level in the logger the level property needs to be provided in the options. level can either be a string e.g. { level: 'debug' } or it can be a structured object with targeted log levels per service e.g. { level: { 'SERVICE_ABC': 'debug', 'SERVICE_XYZ': 'info', '**': 'warn' } }. It follows the pattern documented for builtin loggers.

moleculer.config.js

const logger = new SynLogger({
    level: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace',
});
await logger.setOutput({
    environment: 'docker' | 'gcp', // will attempt environment detection if not present but fallback to 'docker'
    depth: number;  // default 5 applies only to 'docker' environment
});

For convenience a static initialiser has been provided:

const logger = await SynLogger.init({
    level: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace',
    output: {
        environment: 'docker' | 'gcp', // will attempt environment detection if not present but fallback to 'docker'
        depth: number;  // default 5 applies only to 'docker' environment
    },
});

The intended use for the logger is that argument one will be a message string. Argument two as an optional context object:

this.logger.info('my message', {
    extra: 'data',
    for: {
        the: ['logEntry', 'to', 'contain'],
    },
});

consideration has been where the message is omitted, the below would log with a message of "message omitted":

const err = new Error('example');
this.logger.error(err);

this.logger.info({
    extra: 'data',
    for: {
        the: ['logEntry', 'to', 'contain'],
    },
});

To align SynLogger to match MoleculerJS built-in implementation that logger will collect any additional supplied arguments and output all captured arguments as a values entry.

this.logger.info('message', { example: 'data' }, ['logEntry'], 'some string');
// will output a context object like:
{ message: 'message', jsonPayload: { values: [{ example: 'data' }, ['logEntry'], 'some string'] } }

Function Usage

const { writeLogEntry } = require('@synanetics/logging');
// or
import { writeLogEntry } from '@synanetics/logging';

The function will just print to stdout using the structured logging format desired by GCP. Arguments:

  • type - expects string being one of fatal, error, warn, info, debug, trace - unknown values will fallback to structured severity level of 'DEFAULT' but a value MUST be supplied
  • message - expects a string message to represent your log entry - if omitted a message of "message omitted" is used
  • context - expects an object of any shape
writeLogEntry(type: string, context: object);
writeLogEntry(type: string, message: string, context: object);
writeLogEntry(type: string, message: string, context: object, mode: 'human' | 'json');


writeLogEntry('info', 'my message', {
    extra: 'data',
    for: {
        the: ['logEntry', 'to', 'contain'],
    },
});

writeLogEntry('debug', {
    extra: 'data',
    for: {
        the: ['logEntry', 'to', 'contain'],
    },
});

const err = new Error('example');

writeLogEntry('error', err);

writeLogEntry('fatal', 'critical error trying to do something important', err);

// would ouput:
// {YYYY-MM-DD HH:mm} [SEVERITY] message
//  indented pretty printed data..
//
writeLogEntry('fatal', 'critical error trying to do something important', { something: 'here' }, 'human');