Skip to content

feature: define tracing - log time #1

Description

@aoancea

This decorator is going to support the logging of time taken by a method from a class to execute, thus, I define the following interface and its implementation:

public interface IFoo
{
    string Bar(string text);
}

public class Foo : IFoo
{
    public string Bar(string text)
    {
        return text;
    }
}

Before I can talk about the decorator, a mechanism is needed to provide access to data, and more exactly to the elapsed time. For this I define the following interface:

public interface ILogger
{
    void Log(Stopwatch sw);
}

Given the above interfaces, I define the following decorator:

public class Foo_Time_Decorator : IFoo
{
    private readonly IFoo decorated;
    private readonly ILogger logger;

    public Foo_Time_Decorator(IFoo decorated, ILogger logger)
    {
        this.decorated = decorated;
        this.logger = logger;
    }

    public string Bar(string text)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        string result = decorated.Bar(text);

        sw.Stop();

        logger.Log(sw);

        return result;
    }
}

Usage example:

public class ConsoleLogger : ILogger
{
    public void Log(Stopwatch sw)
    {
        Console.WriteLine(sw.ElapsedMilliseconds);
    }
}

class Program
{
    static void(string args)
    {
        IFoo foo = new Foo();
        ILogger logger = new ConsoleLogger();
        IFoo fooDecorator = new Foo_Time_Decorator(foo, logger);

        fooDecorator.Bar("some text");
    }
}

When running a console application, the ElapsedMilliseconds would be displayed in the console.

Note: The wiring of objects will be done using a DI container.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions