Search code examples
azure-application-insights

Does Application Insights have the concept of formatted messages using properties?


The Windows Event Log has the concept of messages with variables pointing to metadata properties. I am wondering if Application Insights can do the same thing. I couldn't find anything on the internet. For example:

const string _loginMessage = "{user} logged in at {time}";
...
telemetryClient.TrackTrace(
    _loginMessage,
    new Dictionary<string, string>
    {
        ["user"] = user.Name,
        ["time"] = DateTime.UtcNow
    });

When rendered and looking at the logs in Application Insights, it would show the full message.

I understand I could wrap TrackTrace and do this myself, but I don't want to if this comes for free.

Thanks


Solution

  • The TrackTrace method does not support this kind of message-format. You need to write your own logic to implement it.

    But for some projects like web app / azure function which has ILogger integrated with Application Insights, you can use the LogInformation method from ILogger. The code like below(it's a web project):

        public IActionResult Index()
        {
            string _loginMessage = "{user} logged in at {time}";
            string user = "myname222";
            string time = "2021-03-03 vvvvv";
    
            _logger.LogInformation(
                _loginMessage,user,time);
    
            return View();
        }
    

    After run the project, you can see the formatted message and properties in azure portal:

    enter image description here