Microsoft Dynamics CRM: Simple File Logging for Plugins (and Workflows)

Well, there are many logging tools out there, but most of them depend on external assemblies. It is (not impossible but) more or less difficult to implement them in plugins.

So I decided to write a very simple file logger for myself. And this is also the tool I use to demonstrate what happens within the execution of plugins in my “Plugin messages – deep dive”. I tested it with Dynamics CRM 2013, but it should work the same way with every other version!

The Logger

The XrmLogger class is very easy to understand. There is a XrmLoggerConfig class where you specify where to write the files and the name you like your logs to have. The filename is a combination of a string and the date. In our Example the name would be “2013-10-09-XrmLoggerDemo.log”. Every day a new file is created. But you can change this very easily.

XrmLoggerConfig config = new XrmLoggerConfig()
            {
                LogDirectoryName = @"C:\LOG",
                LogFileGroup = "XrmLoggerDemo",
                logLevel = LogLevel.VERBOSE
            };

Next step is to get the execution context and do whatever your plugin is supposed to do. In my example I write the entity name, the message and the stage the plugin is running at.

xLog.ialert(String.Format("Entity: {0} => Message: {1} => Stage: {2}", context.PrimaryEntityName, context.MessageName, context.Stage));

So thats it more or less. Compile the code and register the assembly. Next choose the entity and the messages you want to listen at. And here is the result:

09.10.2013 14:27:28.400 :: INFO :: Entity: account => Message: RetrieveMultiple => Stage: 10
09.10.2013 14:27:28.405 :: INFO :: Entity: account => Message: RetrieveMultiple => Stage: 20
09.10.2013 14:27:28.458 :: INFO :: Entity: account => Message: RetrieveMultiple => Stage: 40

Below you find a listing of the complete code and the files do download.

xrlmLogger.cs

using System;
using System.Text;
using System.IO;

namespace xrmLog
{
    public enum LogLevel
    {
        VERBOSE = 0,
        INFO = 10,
        WARNING = 20,
        ERROR = 30,
    }

    public class XrmLoggerConfig
    {
        private string _LogDirectoryName = @"C:\LOG\";
        private string _LogFileName = "{0}-{1}.log";
        private string _LogFileGroup = "XrmAppLog";
        private LogLevel _logLevel = LogLevel.VERBOSE;

        public string LogDirectoryName
        {
            set
            {
                this._LogDirectoryName = value;
            }
            get
            {
                return this._LogDirectoryName;
            }
        }

        public string LogFileName
        {
            set
            {
                this._LogFileName = value;
            }
            get
            {
                return this._LogFileName;
            }
        }

        public string LogFileGroup
        {
            set
            {
                this._LogFileGroup = value;
            }
            get
            {
                return this._LogFileGroup;
            }
        }

        public LogLevel logLevel
        {
            set
            {
                this._logLevel = value;
            }
            get
            {
                return this._logLevel;
            }
        }

    }

    public class XrmLogger
    {

        private Boolean _dologging = true;
        private XrmLoggerConfig _config = new XrmLoggerConfig();

        private FileStream _fileStream;

        public XrmLogger()
        {
            this.init(_config);
        }

        public XrmLogger(string logFileName)
        {
            _config.LogFileName = logFileName;
            init(_config);
        }

        public XrmLogger(XrmLoggerConfig config)
        {
            this._config = config;
            init(config);
        }

        public Boolean doLogging
        {
            set
            {
                this._dologging = value;
            }
            get
            {
                return this._dologging;
            }
        }

        private string getDateTimeString()
        {
            return DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff");
        }

        private string getDateString()
        {
            return DateTime.Now.ToString("yyyy-MM-dd");
        }

        private string getFileName()
        {
            return String.Format(_config.LogFileName, this.getDateString(), _config.LogFileGroup);

        }

        private void init(XrmLoggerConfig config)
        {
            string _LogDirectoryName = config.LogDirectoryName.EndsWith(@"\") ? config.LogDirectoryName : config.LogDirectoryName + @"\";

            string path = String.Format("{0}{1}", _LogDirectoryName, this.getFileName());
            _fileStream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
        }

        public void close()
        {
            _fileStream.Close();
        }

        private void writeFile(string message)
        {
            string line = this.getDateTimeString() + message + Environment.NewLine;
            byte[] info = new UTF8Encoding(true).GetBytes(line);
            this._fileStream.Write(info, 0, info.Length);
            this._fileStream.Flush();
        }

        public void valert(string msg)
        {
            if (this._dologging && _config.logLevel <= LogLevel.VERBOSE)
            {
                writeFile(" :: VERBOSE :: " + msg);
            }
        }

        public void ialert(string msg)
        {
            if (this._dologging && _config.logLevel <= LogLevel.INFO)
            {
                writeFile(" :: INFO :: " + msg);
            }
        }

        public void walert(string msg)
        {
            if (this._dologging && _config.logLevel <= LogLevel.WARNING)
            {
                writeFile(" :: WARNINIG :: " + msg);
            }
        }

        public void ealert(string msg)
        {
            if (this._dologging && _config.logLevel <= LogLevel.ERROR)
            {
                writeFile(" :: ERROR :: " + msg);
            }
        }
    }

}

The Sample Plugin

If you want to write a informational message use ialert, if you want to indicate a warning walert and on errors use the ealert function.

XrmLoggerDemo.cs

using System;
using Microsoft.Xrm.Sdk;

// 
// This is  demo of the XrmLogger class.
// How to use it:
// Create a C:\LOG on the Server and give your CRM Users RW rights
// Compile this class (don't forget to sign it with a strong key!)
// Use the pluginregistrationtool from the CRM.SDK to register the assembly (don't specify sandbox isolation mode! 
// => this plugin works only in onpremise or hosting environments
// deploy it for any message and entity you like
// 

namespace xrmLog
{
    public class XrmLoggerDemo : IPlugin
    {

        public void Execute(System.IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            XrmLoggerConfig config = new XrmLoggerConfig()
            {
                LogDirectoryName = @"C:\LOG",
                LogFileGroup = "XrmLoggerDemo",
                logLevel = LogLevel.VERBOSE
            };

            XrmLogger xLog = new XrmLogger(config);

            xLog.ialert(String.Format("Entity: {0} => Message: {1} => Stage: {2}", context.PrimaryEntityName, context.MessageName, context.Stage));
        }
    }
}

Download Visual Studio 2012 Project:
XrmLoggerDemo

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation