0

I want to build a log file in memory using a StringBuilder, so I have a

private StringBuilder logFile = new StringBuilder();

in my controller class. Later than I append log lines to that object.

But after each request it is cleared. How do I keep the contents during multiple requests/views? What's the best approach?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Oliver Kötter
  • 1,006
  • 11
  • 29

3 Answers3

1

You can use Session or Cache for storing data between requests, eg:

Session["data"] = logFile;

and then retrieve it:

logFile = Session["data"] as StringBuilder;
gzaxx
  • 17,312
  • 2
  • 36
  • 54
  • Thanks, but while it certainly works I wanted to avoid it as I read that it is bad design to use Session variables for that. – Oliver Kötter Feb 28 '13 at 10:59
0

I recommend using log4Net for any logging needs, works like a cham and does exactly what you are looking for.

dada686
  • 433
  • 5
  • 16
0

You could use a static field (make sure to properly synchronize access to it) or directly append the values to a file. Or simply use a logging framework which is designed exactly for that purpose. You don't need to be using 3rd party, .NET already has an excellent logging facilities built-in (look at the System.Diagnostics namespace).

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • what do you mean by "properly synchronize access"? – Oliver Kötter Feb 28 '13 at 11:00
  • You know, standard synchronization techniques, `lock` and stuff, things you do when you need to ensure that a single thread is accessing a shared resource. – Darin Dimitrov Feb 28 '13 at 11:14
  • Thanks, that was the solution. Instead of using a private field in the controller class I simply created a new static class with the static field and its contents are preserved. – Oliver Kötter Feb 28 '13 at 11:25