Extension method for logging. A good idea?

What are the pros and cons of the following extension method, in your opinion?

static class Log
{
    public static string AddToLog(this string input)
    {
        Console.WriteLine(input);
        return input;
    }

    public static string AddToLog(this string input, string format)
    {
        Console.WriteLine(format, input);
        return input;
    }
}

Usage scenario:

class Program
{
    static void Main(string[] args)
    {
        string tableName = "Bills".AddToLog("Default table name is {0}");

        "Starting...".AddToLog();
        "Creating table".AddToLog();
    }
}
+3
source share
7 answers

Well, they are static to begin with, which will make testing more difficult and will be increasingly tightly coupled.

I also personally think something like

Logger.Write("Starting..");

more understandable than

"Starting...".AddToLog();
+10
source

For me it is not very readable.

Just because you can doesn’t mean you should :)

+2
source

, Ruby, . , , , , .

# .

, . : ? - , , , , log4net, .

+2

. . , . ( , )

, , , - , , . .ToX(), MPH - , , .

+1

Console.WriteLine

API ( ) , .
, log4net .Error . , .

, , .

+1

, . , , .., .

, String . , , . , , .

+1

The biggest problem with this approach is that it is almost impossible to embed dependencies in static / extension methods very cleanly. This means that your logging solution (assuming it should become more complex than dumping things in stdout / console / debug) must be deployed and configured for any type of testing in the project. Someday.

+1
source

Source: https://habr.com/ru/post/1760588/


All Articles