Simple logging for ASP.NET Web API clients

This is a quick and dirty example of how you can enable a simple form of logging for clients using ASP.NET Web API. I used log4net and an extremely simple controller to achieve this.

Controller has only a couple of tricks to get the body of the POST as it is regardless of the content type. The rest is pretty straight forward.

{% highlight c# %} public class LogController : ApiController {

public async Task<string> Post()
    string message = await Request.Content.ReadAsStringAsync();

    string logger = GetHeaderOrDefault("X-Logger", "main");
    string logLevel = GetHeaderOrDefault("X-LogLevel", "debug");

    ILog log = LogManager.GetLogger("client." + logger);

    if (logLevel == "error") log.Error(message);
    else if (logLevel == "warn") log.Warn(message);
    else if (logLevel == "info") log.Info(message);
    else log.Debug(message);

    return "OK " + DateTime.Now;

} {% endhighlight %}

Another simple trick is with the log4net configuration. This is to keep the log file separate from the rest of the logging in the application:

{% highlight xml %} <?xml version=“1.0” encoding=“utf-8” ?>

{% endhighlight %}

You might find the rolling file appender interesting too which makes sure the log files won’t go out of hand in the long run.

Full working example is available on GitHub under mtmk.


February 28, 2015 | 197 Words

Ziya Suzen (Maxwell Troy)'s personal notes on software development and related technical subjects.