Assaf Sheep
Assaf Sheep

Reputation: 583

Azure Functions - shared objects between different invocations

I am using Azure Functions with Node.Js.

I created a custom Node.js logger module which uses azure function's context object and write to the function's log which is displayed in the Azure portal UI. Since we're using it in multiple places we defined it as singleton object and we injected the function's context object to it.

Then, we found out that all the other functions executions were using the same logger object... and were not logging the data to their own context log. This is very strange for us since we expected that each function invocation is isolated and there are no shared modules between different invocations.

This is the azure function code:

var Logger = require( '../custom_modules/logger/customLogger.js');

module.exports = function (azureContext) {
    function infoFn(msg){
        azureContext ? azureContext.log(msg) : console.log(msg);
    }
    function errorFn(msg){
        azureContext ? azureContext.log(msg) : console.error(msg);
    }

    var logger = Logger(infoFn, errorFn);

    logger.info('function was triggered');
    azureContext.done();

  }

And this is the logger module code:

var _customLogger;

var CustomLogger = function (info, error) {
    this.error = error;
    this.info = info;
};

function logger(info, error) {
    if (!_customLogger) {
        _customLogger = new CustomLogger(info, error);
    } else {
        if(info){
            _customLogger.info = info;
        }
        if(error){
            _customLogger.error = error;
        }
    }
    return _customLogger;
}

module.exports = logger;

Is it suppose to be like this? We expected that each function invocation will be isolated.

Upvotes: 1

Views: 1460

Answers (1)

mathewc
mathewc

Reputation: 13568

The logger instance passed into your function is indeed different for each function and each function invocation. We create a new instance for each invocation.

I believe any issues you're seeing with multiple invocations interfering with each others logging is due to your custom logger component. The problem is that your shared custom singleton logger is capturing (and sharing) an invocation specific Azure logger across invocations. This is true because you're returning a singleton to various invocations and all of those invocations are mutating it.

Whatever your goal is in wrapping our logging infrastructure, you should remove this singleton behavior to restore isolation. We've also recently made a change to our logger to expose methods for different log levels log, verbose, error, warn. That will roll out very soon.

Upvotes: 2

Related Questions