PLCnext / CSharpExamples

Collection of various C# sample code for PLCnext Technology controllers.
MIT License
13 stars 11 forks source link

Write a log to PLC Next log file #21

Open MaltarIvan opened 4 weeks ago

MaltarIvan commented 4 weeks ago

One example of the feature that I find useful is writing a log to a PLC Next log file.

For example: if you catch an exception in your C# code, you could write the exception message to log file for diagnostic purposes.

Is there such possibility in PLC Next development tools?

martinboers commented 4 weeks ago

I think the Log class might help in this case:

image

This should log a message to the file /opt/plcnext/logs/Output.log.

Note that, by default, DEBUG and TRACE messages are not recorded in that log file. More information here:

https://plcnext.help/te/PLCnext_Runtime/output_log.htm

MaltarIvan commented 4 weeks ago

Thank you for the answer. Is there maybe an example of using the methods in Log class? Specifically I am interested in how to define the format string and 'args' arguments.

martinboers commented 4 weeks ago

It just uses standard C# formatting.

This example is based on the C# function template, and writes the value of the two input parameters to the log file:

   [Function]
   public static class Function1
   {
       [Execution]
       public static bool __Process(
           [Input] short IN1,
           [Input, DataType("WORD")] ushort IN2)
       {
           bool Function1 = false;

           if (IN1 + IN2 == 2)
               Function1 = true;

           Log.Info("Hello. IN1 = {0} and IN2 = {1}", IN1, IN2);

           return Function1;
       }
   }

There's resources online that explain C# output formatting, e.g.: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

MaltarIvan commented 3 weeks ago

Ok, I understand now. Thanks for the help!