Book a Demo

Author Topic: Creating Files and Using Log4Net  (Read 7428 times)

Pedro

  • EA Novice
  • *
  • Posts: 15
  • Karma: +0/-0
    • View Profile
Creating Files and Using Log4Net
« on: May 13, 2013, 10:57:46 pm »
Hello,

I have a multiproject add-in solution. Also, I have a setup Wix project, which I use to install my addin.

I wanted to log the execution of my add-in, and so I've  chosen log4net. After researching in how to log libraries with it, I deployed a version which used a configuration file. It did not worked. Then, I created a second version which loads programmaticaly https://logging.apache.org/log4net/release/manual/configuration.html my configuration to then start logging. It also did not worked.

Finally, I coded my addin to just create a simple file using StreamWriter and the files are not being created, but without any error or message. I started thinking that this may be a permission issue, and I granted full permissions for trusted installers, my user, everyone, without success.

I appreciate any help. How do you usually deploy your add-ins? And how do you log then, if you do? I can give more code details if needed.

Best,

Pedro

Geert Bellekens

  • EA Guru
  • *****
  • Posts: 13523
  • Karma: +574/-33
  • Make EA work for YOU!
    • View Profile
    • Enterprise Architect Consultant and Value Added Reseller
Re: Creating Files and Using Log4Net
« Reply #1 on: May 14, 2013, 04:00:06 pm »
Hi Pedro,

Aren't you over-thinking the logging part?
When I needed some kind of logging I simply create a small static logger class.

Code: [Select]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ACVModellingTools.Util
{
    public static class Logger
    {
        private static string logFileName = @"c:\temp\ModellingToolkit.log";
        /// <summary>
        /// set the log file name
        /// </summary>
        /// <param name="fileName">the name of the log file</param>
        public static void setLogFileName(string fileName)
        {
            logFileName = fileName;
        }
        /// <summary>
        /// log a message
        /// </summary>
        /// <param name="logmessage">the message to be logged</param>
        public static void log(string logmessage)
        {
            System.IO.StreamWriter logfile = new System.IO.StreamWriter(logFileName,true);
            logfile.WriteLine( System.DateTime.Now.ToString("o") + " " + logmessage);
            logfile.Close();
        }
        /// <summary>
        /// log an error
        /// </summary>
        /// <param name="logmessage">the error message</param>
        public static void logError(string logmessage)
        {
            log("Error: " + logmessage);
        }
        /// <summary>
        /// log a warning
        /// </summary>
        /// <param name="logmessage">the warning message</param>
        public static void logWarning(string logmessage)
        {
            log("Warning: " + logmessage);
        }
    }
}

As for using configuration files, that's a bit more complicated then usual because you are not creating an exe, but a dll.

I'm using a configuration file in my EA Navigator add-in. I've moved all of the configuration stuff into one Class: NavigatorSettings
I'm not sure whether it is the best way to deal with config files, but it works for me.

Geert

mateiacd

  • EA User
  • **
  • Posts: 24
  • Karma: +0/-0
    • View Profile
Re: Creating Files and Using Log4Net
« Reply #2 on: September 15, 2017, 09:54:03 pm »
>I wanted to log the execution of my add-in, and so I've  chosen log4net.

In what programming language have you written the add-in ?

Below is an example using Visual Studio 2012 Express Edition and C#

1.   Create a <<yourAddin>> Class library DLL. Choose of course your own suitable name for <<yourAddin>>

2.   Set the checkbox [ x ] Register for COM Interop  in the Project Settings -> Build tab

3.   Build the project.

If you run with Administrative rights,  Visual Studio will also register the DLL with regasm.exe.

Or if you prefer:

Register manually <<yourAddin>>.DLL with a command below similar to this:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe D:\Temp\<<yourAddin>>.dll /codebase

4.     Copy the log4net.config configuration file near the D:\Temp\<<yourAddin>>.dll

          Or if you prefer, copy the log4net.config file in the Sparx Enterprise Architect folder
"C:\Program Files (x86)\Sparx Systems\EA\log4net.config"
But this requires Administrative rights and in this case is not necessary to call log4net.Config.XmlConfigurator.ConfigureAndWatch

5.     In AssemblyInfo.cs, add the line below to the end of the file

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

          Or if you prefer, set a full path to the configuration file, in which case, again, is not necessary to call log4net.Config.XmlConfigurator.ConfigureAndWatch

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "D:\\Temp\\log4net.config", Watch = true)]

6.    Write the code below in the main class of the DLL

Code: [Select]
using EA;
using log4net;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

[ComVisible(true)]
public class AddIn
{
        private ILog log;

        public string EA_Connect(Repository repository)
        {
         
     //setup the configuration file
     //in this example, at step 4, I decide to use the 
     //log4net.config configuration file placed near the <<yourAddin>>.DLL file

    //this is is not necessary if the log4net.config is in the Sparx Enterprise Architect folder or a full path is specified in AssemblyInfo.cs

            string dllFullPath = Assembly.GetExecutingAssembly().Location;
            String logFile = Path.GetDirectoryName(dllFullPath)+"\\log4net.config";
         
//https://stackoverflow.com/questions/21166126/log4net-separate-config-file-not-working           
            FileInfo fileInfo = new FileInfo(logFile);
            log4net.Config.XmlConfigurator.ConfigureAndWatch(fileInfo);


             log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
             log.Info("\r\nEA_Connect '" + repository.ConnectionString + "'");

            return "AddIn connected";
        }
….
}


Example of log4net.config file

Code: [Select]
<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    </configSections>

 
 <log4net>
   
<appender name="MyAppender" type="log4net.Appender.ConsoleAppender">
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level %logger - %message%newline" />
  </layout>

</appender>


   <appender name="MyFileAppender" type="log4net.Appender.FileAppender">
     <file value="D:\Temp\MainLog.txt" />
     <appendToFile value="true" />
     <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
     <layout type="log4net.Layout.PatternLayout">
       <conversionPattern value="%date{dd-MM-yyyy HH:mm:ss} %level %logger - %message%newline" />
     </layout>
   </appender>

 <root>
      <level value="ALL"/>
      <appender-ref ref="MyAppender" />
      <appender-ref ref="MyFileAppender" />

    </root>

 </log4net>

<startup><supportedRuntime version="v2.0.50727"/></startup>
 
</configuration>

« Last Edit: September 15, 2017, 10:25:12 pm by mateiacd »