C# API - logging messages to logfile via Console.WriteLine() could cause an IO Exception

Find and share HowTos to various installations / configurations!
1 post • Page 1 of 1
eivanovic
Posts:78
Joined: Wed Sep 03, 2014 2:35 pm

C# API - logging messages to logfile via Console.WriteLine() could cause an IO Exception

Post by eivanovic »

Maybe you get asked once about C# API and how to log messages to a logfile.
In our examples (C# Docu) we use the standard console output called Console.WriteLine which is a native C# command. This command is forwarded via the WinCC OA C# API to PVSS_II.log.

By the way this is not very safe, because it could be seen in the API Code that the override modifier of Console.WriteLine() just do an open file command for PVSS_II.log and append the message to it. In case of a logfile switch you would get an
System.IOException which will crash your manager if the exception is not handled.

There are currently 2 ways to get rid of it:

1. Encapsulate the Console.WriteLine() into an own method like the example below (Take care about Thread Safety!!!)
2. Use instead of Console.WriteLine() the wrapped C++ Methods of ErrHdl which are available in the ETM.WCCOA.internal namespace

Using the ErrHdl is much safer because fileswitch is handled there by default.

Code: Select all

 
//To make Console.WriteLine() more safe, try to encapsulate the function like this code example: 

void writeToLog(string text) 
{ 
  logbuffer.append(text + "\\n"); //StringBuilder type 
  try 
  { 
    Console.WriteLine(logbuffer); 
    logbuffer.clear();
  } 
  catch(Exception e) 
  { 
    
  } 
} 


1 post • Page 1 of 1