1

I have a block of code with logging and I am trying to append a value to each line of log for the entire block, is it possible to append for an entire block of code

Sample code

void MyMethod(){
//code
log
log
//code
log
//code
}
DoIt
  • 3,270
  • 9
  • 51
  • 103
  • like `log.Info(MyString+"Strat")` ? or you want to build a string during the code block and log it at the end? – Drag and Drop May 03 '18 at 15:08
  • log4net can log the method name and it can also log custom context properties that you can give a scope, but I'm really not clear on what you're after, here. A before/after example would be nice. – Jeroen Mostert May 03 '18 at 15:11
  • Or you want to increment the same line of log during the block like "Count : 1 2 3 4 5" where 12345 will be add one after each other – Drag and Drop May 03 '18 at 15:11
  • What do you want logged? – ChargerIIC May 03 '18 at 15:11
  • @ChargerIIC I want to add time when control entered the block to all logs in that block and I want to do it at one place without repeatedly adding manually at each line of log – DoIt May 03 '18 at 15:13
  • @Dolt this sounds like https://stackoverflow.com/questions/533804/append-current-date-to-log-file-with-log4net Log4Net has a config file where you can set things like this. – ChargerIIC May 03 '18 at 15:15
  • @ChargerIIC This one does it for the entire log but I just want it for a single block – DoIt May 03 '18 at 15:17
  • You could use a [custom context property](http://logging.apache.org/log4net/release/manual/contexts.html) and include it in your pattern, but it's probably much simpler to introduce a lambda or local function along the lines of `DateTime start = DateTime.Now; Action log = s => logger.Info($"{start}: {s}");`, unless you're really doing this everywhere. – Jeroen Mostert May 03 '18 at 15:23

1 Answers1

0

Since you only want the timestamps for log entries for this method, you can use a quick private method to acheive your goals:

void MethodToCall(){
  logWithTime("Entering Method");
  //DoStuff
  logWithTime("ExitingMethod");
}

void logWithTime(string logText){
  logger.Info(string.format("MethodToCall: {0} {1}", logText, DateTime.Now.ToString());
}
ChargerIIC
  • 1,620
  • 1
  • 33
  • 47