Search code examples
c#azuretimestampazure-application-insightstelemetry

Can I mock data (timestamps) in Application Insights?


I am using Application Insights to view Telemetry for my application. As a demo I want to populate App Insights with data so I can generate detailed graphs and charts to show potential user scenarios. I want my data to span week even months, but I don't have time to wait that long.

Is it possible to manual place a timestamp/date into my Telemetry call in my app, like a few months in the past, so that I can have information from that time?


Solution

  • You can use ITelemetryInitializer to achieve that.

    Method 1:

    You can define a custom property which you can define the custom timestamp, instead of change the timestamp directly:

    If use this method, in your custom class which implements ITelemetryInitializer, the code like below:

        public class MyTelemetryInitializer : ITelemetryInitializer
        {
            public void Initialize(ITelemetry telemetry)
            {
                DateTimeOffset dateTimeOffset = new DateTimeOffset(new DateTime(2020, 1, 10));
    
                //define a custom property, which is a date time
                telemetry.Context.GlobalProperties["Custom_timestamp"] = dateTimeOffset.ToString();
    
            }
         }
    

    After execute the code, you can see this property is added to each telemetry data in azure portal:

    enter image description here

    When you build your query to generate graph, you can take use of this custom property(Note: this property is string type, so you may use the built-in function todatetime() to convert it to datetime type) instead of using timestamp.

    Method 2:

    This method tries to directly changes the timestamp. I can see the timestamp is changed locally, it does not send to application insights. So currently, I suggest you should use method 1.

    The code like below:

    public class MyTelemetryInitializer : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            //try to directly change the Timestamp, it changes successfully in local(in visual studio), but it does not send to application insights.
            telemetry.Timestamp = new DateTimeOffset(new DateTime(2020, 1, 10));
    
        }
     }