/// <summary> /// Objects to XML. /// </summary> /// <param name="output">The output.</param> /// <returns></returns> public static string ObjectToXml(object output) { string objectAsXmlString; System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType()); using (System.IO.StringWriter sw = new System.IO.StringWriter()) { try { xs.Serialize(sw, output); objectAsXmlString = sw.ToString(); } catch (Exception ex) { objectAsXmlString = ex.ToString(); } } return objectAsXmlString; }
Tag Archives: Logging
How To Easily Add Log4Net To Your .NET Project
- Download Log4Net binaries –> http://logging.apache.org/log4net/download_log4net.cgi
- Add Reference to Log4Net.dll in your project
- Create new “Logs” folder and ensure Web App/Site has Write privileges to this directory
- Add the following to Global.asmx
/// <summary> /// Gets the application log4net log instance. /// </summary> /// <value>The log.</value> public ILog log { get { return LogManager.GetLogger("AppLogger"); } } void Application_Start(object sender, EventArgs e) { // Code that runs on application startup log4net.Config.XmlConfigurator.Configure(); }
- Add Log4Net config section and declaration into web.config/app.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <appSettings> </appSettings> <log4net> <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="Logs/application.log"/> <appendToFile value="true"/> <rollingStyle value="Composite"/> <datePattern value="yyyyMMdd"/> <maxSizeRollBackups value="10"/> <maximumFileSize value="5MB"/> <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%n DATE: %date{MM/dd/yyyy HH:mm:ss} %n THREAD: [%thread] %n LEVEL: %-5level %n USER ID: %identity %n CLASS: %type{1} %n METHOD: %M %n LOCATION: %location %n MESSAGE: %message %n "/> </layout> </appender> <root> <level value="DEBUG"/> <appender-ref ref="LogFileAppender"/> </root> </log4net> </configuration>
- Add private static readonly property referencing ILog
class Program { /// <summary> /// Logging /// </summary> //private readonly ILog Logger = DecisionLogManager.GetLogger(typeof(UC4Request)); private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
- Call Error method to log error
catch (Exception ex) { // Log to local log file log.Error("Error", ex); }
- You can also call other methods (Info) to output debug information
log.Info(responseOutput + Environment.NewLine + Base.HelperFunctions.ObjectToString(keywordClientReply, DisplayMode.HTML) );