1

So I would like to log an event in c#. For example I would like to have it log every time a button is pressed into a .txt file and the file is used each time the button(s) are selected vs creating a new .txt file. I have no idea how to do this or even where to start. I do not want some extravagant code base to do it with. Does anyone know a quick, simple and to the point way of doing this?

Using VS 2015 with .NET 4.5 target framework.

William Hodges
  • 661
  • 10
  • 24
  • In general "what are way to do X" questions are too broad for SO. You may consider reading older identical questions like http://stackoverflow.com/questions/20185015/how-to-write-log-file-in-c to improve your post and make it more narrow scoped. – Alexei Levenkov Sep 05 '15 at 00:09

3 Answers3

3

I believe that you are looking for NLog, check the official tutorial.

Your finally code will look something like this:

using NLog;

public class YourClass
{
  private static Logger logger = LogManager.GetCurrentClassLogger();

  public void ButtonWasPressedEvent()
  {
    logger.Info("Thanks for pressing dude!");
  }
}

The installation can be donde using NuGet, that should be very simple.

Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
1

The venerable log4net is the Apache Foundation solution for a .NET logger based on a java predecessor, log4j.

It is also installable via NuGet but does require some non-trivial configuration due to its power and flexibility. log4net can be configured in code or in the project configuration files (app.config or web.config).

Logs can be stored in flat files or in a database system of your choosing, or both, via the extensive set of available appenders. For example, the RollingFileAppender writes to a file which "rolls over" (starts a new file) at a specified size or interval:

<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="log.txt" />
  <appendToFile value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="100KB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>

Multiple appenders can be used concurrently to direct log entries to multiple destinations. Also, multiple loggers can be defined, each with their own set of appenders.

The full feature set is listed here.

Peter Gluck
  • 8,168
  • 1
  • 38
  • 37
0

Here's an example from MSDN, it covers the file part. https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

Andreas Turku
  • 438
  • 3
  • 9