private void InitializeLogFile() { _semaphoreSlim.Wait(); try { LogFileName = Path.Combine(_workingFolder, $"WTS_{Configuration.Current.Environment}_{DateTime.Now.FormatAsDateForFilePath()}.log"); if (!Directory.Exists(_workingFolder)) { Directory.CreateDirectory(_workingFolder); } if (CheckLogFileInUse(LogFileName)) { LogFileName = LogFileName.Replace(".log", $"_{Guid.NewGuid().ToString()}.log"); } StartLog(); } catch (Exception exception) { Trace.TraceError($"Error initializating log file. Exception:\r\n{exception.ToString()}"); } finally { _semaphoreSlim.Release(); } }
void _Init() { LogFileEnabled = ParseBool("LogFileEnabled", false); if (!LogFileEnabled) { return; } _LogFileAutoFlush = ParseBool("LogFileAutoFlush", false); // File reset options. LogFileTimeout = ParseSpan("LogFileTimeout", new TimeSpan()); LogFileName = ParseString("LogFileName", ""); // Enable rolling by default if file name looks like daily. var defaultRolling = LogFileName.Contains("MMdd}"); LogFileRolling = ParseBool("LogFileRolling", defaultRolling); if (string.IsNullOrEmpty(LogFileName)) { // Suffix pattern. var defautlSuffix = LogFileRolling // Rolling resets daily by default. ? "{0:yyyyMMdd}.txt" // Use current date when creating new file. : "{0:yyyyMMdd_HHmmss}.txt"; // File prefix to make it unique. var defaultPrefix = string.IsNullOrEmpty(_configPrefix) ? GetAssemblyName() : _configPrefix; // Generate unique file name. var fileName = string.Format("{0}\\{1}{2}", GetLogFolder(), defaultPrefix, defautlSuffix ); LogFileName = fileName; } }
/// <summary> /// Initialises a log file writer and returns the delegate to use. /// </summary> /// <param name="filename">The filename to write to (not including path).</param> /// <returns>An AddEntryDelegate that can be added to Log.OnNewLogEntry.</returns> public static AddEntryDelegate WriteToFile(string filename) { try { LogFileName = Path.Combine(Application.StartupPath, filename); bool append = false; if (File.Exists(LogFileName)) { // get last modified time if (new FileInfo(LogFileName).LastWriteTime > DateTime.Now.AddSeconds(-4)) { // modified in last 4 seconds: just transitioned sleep <=> running append = true; } else { // overwrite, but keep previous log string logfilename2 = LogFileName.Replace(".log", ".prev.log"); if (File.Exists(logfilename2)) { File.Delete(logfilename2); } File.Move(LogFileName, logfilename2); } } // open log file logfile = new StreamWriter(LogFileName, append); ((StreamWriter)logfile).AutoFlush = true; // write header if (!append) { logfile.WriteLine("{0} v{1}", Application.ProductName, Application.ProductVersion); logfile.WriteLine(Application.ExecutablePath); logfile.WriteLine("Log created at {0:ddd, dd MMM yyyy HH:mm:ss G\\MTzzz}", DateTime.Now); } // return AddEntryDelegate return(AppendToLogFile); } catch { // if error, return null AddEntryDelegate logfile = null; return(null); } }
public void CreateTest() { Assert.AreEqual( "000101010000000000000.[0].log", LogFileName.Create(new DateTime(0), null, null, false) ); Assert.AreEqual( "0001-01-01_00-00-00+0000000.[0].log", LogFileName.Create(new DateTime(0), null, null, true) ); }
protected override void Execute(CodeActivityContext context) { strFilePath = LogFileName.Get(context); strMessage = Message.Get(context); string strFullPath = Path.Combine(Directory.GetCurrentDirectory(), strFilePath); using (StreamWriter file = new StreamWriter(strFullPath, true)) { file.WriteLine(strMessage + " :" + System.DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")); } }
private string CreateFileName() { string result; string ticks = DateTime.Now.Ticks.ToString(); if (LogFileName.Contains(".")) { string extension = LogFileName.Substring(LogFileName.LastIndexOf(".")); string fileName = LogFileName.Substring(0, LogFileName.LastIndexOf(".")); fileName = string.Format("{0}[{1}]{2}", fileName, ticks, extension); result = fileName; } else { string fileName = string.Format("{0}[{1}]", LogFileName, ticks); result = fileName; } SavedLogFileName = result; return(result); }
public ChoLoggableObject GetMe(Type type) { ChoGuard.ArgumentNotNull(type, "Type"); if (_singletonElement == null) { lock (SyncRoot) { if (_singletonElement == null) { _singletonElement = new ChoSingletonLoggableObject(); _singletonElement.LogDirectory = LogDirectory; _singletonElement.LogFileName = LogFileName.IsNullOrEmpty() ? ChoPath.AddExtension(type.FullName, ChoReservedFileExt.Log) : LogFileName; _singletonElement.LogCondition = LogCondition; _singletonElement.LogTimeStampFormat = LogTimeStampFormat; } } } return(_singletonElement); }
/// <summary> /// Close the log file, writing out final cached information. /// </summary> public void Close() { if (LoggingEnabled && m_LogFile != null) { int total = 0; ProcessLogTableStart("Entities Processed", "Entity Type"); foreach (KeyValuePair <IFCEntityType, int> entry in m_ProcessedEntities) { WriteLineNoBreak("<tr><td>" + entry.Key.ToString() + "<td>" + entry.Value); total += entry.Value; } ProcessLogTableEnd(total); total = 0; ProcessLogTableStart("Elements Created", "Element Type"); foreach (KeyValuePair <CreatedElementsKey, int> entry in m_CreatedElements) { Write("<tr><td>"); if (!string.IsNullOrWhiteSpace(entry.Key.CatName)) { Write("(" + entry.Key.CatName + ") "); } WriteLineNoBreak(entry.Key.ElemName + "<td>" + entry.Value); total += entry.Value; } ProcessLogTableEnd(total); // Copy existing .log file, if any, to this file. // For now, assume name of original log file = logFileName - ".html" if (LogFileName.EndsWith(".log.html")) { string originalLogFileName = LogFileName.Substring(0, LogFileName.Length - 5); try { // ODA_TODO: Remove this when we remove the EDM toolkit. if (File.Exists(originalLogFileName)) { StreamReader originalLogFile = new StreamReader(originalLogFileName); if (originalLogFile != null) { WriteLineNoBreak("<A NAME=\"ToolkitMessage\"></A>"); WriteLineNoBreak("Toolkit Log"); WriteLine(""); string originalLogContents = null; while ((originalLogContents = originalLogFile.ReadLine()) != null) { WriteLine(originalLogContents); } originalLogFile.Close(); File.Delete(originalLogFileName); } } } catch { } } WriteLine(""); WriteLine("Importer Version: " + IFCImportOptions.ImporterVersion); m_LogFile.Close(); } m_LogFile = null; LoggingEnabled = false; LogFileName = null; }
public override ChoBaseConfigurationElement GetMe(Type type) { ChoGuard.ArgumentNotNull(type, "Type"); if (_configurationElement == null) { lock (SyncRoot) { if (_configurationElement == null) { object customConfigurationSectionHandler = Activator.CreateInstance(_configurationSectionHandlerType) as IChoCustomConfigurationSectionHandler; if (customConfigurationSectionHandler == null) { throw new ChoConfigurationConstructionException(String.Format("Missing {0} custom configuration section handler.", _configurationSectionHandlerType.FullName)); } if (!(customConfigurationSectionHandler is IChoCustomConfigurationSectionHandler)) { throw new ChoConfigurationConstructionException(String.Format("Mismatched {0} custom configuration section handler type specified.", _configurationSectionHandlerType.FullName)); } _configurationElement = new ChoCustomConfigurationElement(customConfigurationSectionHandler as IChoCustomConfigurationSectionHandler, _parameters); _configurationElement.DefaultConfigSectionHandlerType = ConfigSectionHandlerType; _configurationElement.ConfigFilePath = ConfigFilePath; ChoStandardConfigurationMetaDataInfo standardConfigurationMetaDataInfo = new ChoStandardConfigurationMetaDataInfo(); standardConfigurationMetaDataInfo.BindingMode = BindingMode; if (ConfigStorageType != null) { standardConfigurationMetaDataInfo.ConfigStorageType = ConfigStorageType.AssemblyQualifiedName; } standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo = new ChoConfigurationMetaDataLogInfo(); standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo.LogCondition = LogCondition; standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo.LogTimeStampFormat = LogTimeStampFormat; standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo.LogDirectory = LogDirectory; standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo.LogFileName = LogFileName.IsNullOrEmpty() ? ChoPath.AddExtension(type.FullName, ChoReservedFileExt.Log) : LogFileName; standardConfigurationMetaDataInfo.Defaultable = Defaultable; _configurationElement.MetaDataInfo = standardConfigurationMetaDataInfo; LoadParameters(_configurationElement); } } } return(_configurationElement); }
private void InitializeConfigElement(ChoBaseConfigurationElement configElement, Type type) { if (configElement == null) { return; } configElement.DefaultConfigSectionHandlerType = ConfigSectionHandlerType; configElement.ConfigFilePath = ConfigFilePath; ChoStandardConfigurationMetaDataInfo standardConfigurationMetaDataInfo = new ChoStandardConfigurationMetaDataInfo(); standardConfigurationMetaDataInfo.BindingMode = BindingMode; if (ConfigStorageType != null) { standardConfigurationMetaDataInfo.ConfigStorageType = ConfigStorageType.AssemblyQualifiedName; } standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo = new ChoConfigurationMetaDataLogInfo(); standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo.LogCondition = LogCondition; standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo.LogTimeStampFormat = LogTimeStampFormat; standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo.LogDirectory = LogDirectory; standardConfigurationMetaDataInfo.ConfigurationMetaDataLogInfo.LogFileName = LogFileName.IsNullOrEmpty() ? ChoPath.AddExtension(type.FullName, ChoReservedFileExt.Log) : LogFileName; standardConfigurationMetaDataInfo.Defaultable = Defaultable; standardConfigurationMetaDataInfo.IgnoreCase = IgnoreCase; standardConfigurationMetaDataInfo.Silent = Silent; configElement.MetaDataInfo = standardConfigurationMetaDataInfo; LoadParameters(configElement); ChoConfigurationMetaDataManager.SetDefaultMetaDataInfo(configElement); }
internal void Refresh(bool refresh) { if (_inLoadingProcess) { return; } lock (SyncRoot) { if (ConfigObject is IChoConfigurationParametersOverridable) { ((IChoConfigurationParametersOverridable)ConfigObject).OverrideParameters(this); } _modifiedStateObject.ResetModified(); bool isDirty = false; bool errorHandled = false; bool canTraceOutput = true; bool hasErrors = false; this[ChoConfigurationConstants.FORCE_PERSIST] = false; _inLoadingProcess = true; ChoConfigSection prevConfigSection = ConfigSection; if (ConfigSection != null) { ConfigSection.StopWatching(); } try { if (ConfigObject != null) { //ChoConfigurationObjectErrorManagerService.ResetObjectErrors(ConfigObject); if (ConfigObject is ChoInterceptableObject) { ChoInterceptableObject interceptableObject = ConfigObject as ChoInterceptableObject; interceptableObject.SetDirty(false); interceptableObject.SetSilent(false); interceptableObject.SetInitialized(false); interceptableObject.IsConfigObjectSilent = Silent; } } GetConfig(ConfigObjectType, refresh); } catch (ConfigurationErrorsException configErrorsEx) { bool isModified = false; errorHandled = SetNThrowException(configErrorsEx, ref isModified); _modifiedStateObject.SetModified(isModified); } catch (TypeInitializationException typeEx) { bool isModified = false; errorHandled = SetNThrowException(typeEx, ref isModified); _modifiedStateObject.SetModified(isModified); } catch (ChoFatalApplicationException) { canTraceOutput = false; throw; } catch (Exception ex) { bool isModified = false; errorHandled = SetNThrowException(ex, ref isModified); _modifiedStateObject.SetModified(isModified); } finally { if (ConfigSection != null && ConfigObject is ChoConfigurableObject) { //Call Notify Property Changed for all default values CallNotifyPropertyChangedForAllDefaultableMembers(); ConfigSection.Initialize(); } if (ConfigSection != null && ConfigSection.ConfigLoadException != null) { bool isModified = false; errorHandled = SetNThrowException(ConfigSection.ConfigLoadException, ref isModified); _modifiedStateObject.SetModified(isModified); } ////Update configuration meta data information //if (ConfigSection != null && ConfigSection.MetaDataInfo != null) // ApplyConfigMetaData(ConfigSection.MetaDataInfo); //Print the output to file if (canTraceOutput) { //Set default trace output file name if (LogFileName.IsNullOrEmpty()) { LogFileName = ChoPath.AddExtension(ConfigObject.GetType().FullName, ChoReservedFileExt.Log); } //if (ConfigSection is IChoCustomConfigSection) //{ // if (ConfigSection.ConfigData != null) // ConfigSection.ConfigObject = ConfigSection.ConfigData as ChoConfigurableObject; // ChoObjectManagementFactory.SetInstance(ConfigObject); //} if ((ConfigSection == null || ConfigSection.ConfigData == null) && !_defaultable /*&& !_persistable*/) { throw new ChoConfigurationConstructionException(String.Format("Failed to load '[{0}]' configuration section.", this._configElementPath)); } else { if (prevConfigSection != null) { prevConfigSection.Dispose(); } if (ConfigObject is ChoConfigurableObject) { ((ChoConfigurableObject)ConfigObject).SetReadOnly(true); } bool hasConfigSectionDefined = ConfigSection != null ? ConfigSection.HasConfigSectionDefined : false; try { if (!errorHandled) { if (!(ConfigSection is IChoCustomConfigSection)) { if (hasConfigSectionDefined) { _modifiedStateObject.SetModified(ExtractNPopulateValues(ref hasErrors, ref isDirty)); } else { _modifiedStateObject.SetModified(AssignToFallbackOrDefaultValues(ref isDirty)); } } else { if (hasConfigSectionDefined) { //isModfied = true; if (ConfigSection == null) { _modifiedStateObject.SetModified(AssignToFallbackOrDefaultValues(ref isDirty)); } else if (!ChoObject.Equals(ConfigSection, prevConfigSection)) { _modifiedStateObject.SetModified(true); } else { _modifiedStateObject.SetModified(AssignToFallbackOrDefaultValues(ref isDirty)); } } else { _modifiedStateObject.SetModified(AssignToFallbackOrDefaultValues(ref isDirty)); } } } if (!hasErrors) { hasErrors = ChoConfigurationObjectErrorManagerService.ContainsObjectError(ConfigObject); } ChoObjectInitializer.Initialize(ConfigObject, false, ConfigSection != null ? ConfigObject : null); SetWatcher(false); if (ConfigObject is ChoInterceptableObject) { ChoInterceptableObject interceptableObject = ConfigObject as ChoInterceptableObject; if (interceptableObject.Dirty) { isDirty = interceptableObject.Dirty; } //if (interceptableObject.IsModified) //{ // isModfied = interceptableObject.IsModified; //} interceptableObject.SetDirty(false); //interceptableObject.SetSilent(false); interceptableObject.SetInitialized(true); } if (ConfigObject is ChoConfigurableObject) { bool invokeObjectLoaded = /* isDirty || */ _firstTime || _modifiedStateObject.IsModified; if (invokeObjectLoaded || hasErrors) { TraceOutput(false); if (invokeObjectLoaded) { ((ChoConfigurableObject)ConfigObject).RaiseAfterConfigurationObjectLoaded(); } } //if (isDirty) //{ // TraceOutput(false); // ((ChoConfigurableObject)ConfigObject).OnAfterConfigurationObjectLoaded(); //} //else if (hasErrors) // TraceOutput(false); } else { TraceOutput(false); } if (!isDirty && ConfigSection != null) { isDirty = ConfigSection.IsMetaDataDefinitionChanged; } } finally { if (prevConfigSection != null) { prevConfigSection.Dispose(); prevConfigSection = null; } if (ConfigObject is ChoConfigurableObject) { ((ChoConfigurableObject)ConfigObject).SetReadOnly(false); } if (!hasConfigSectionDefined || isDirty || hasErrors) { if (_defaultable) { Persist(false, null); } } else if ((bool)this[ChoConfigurationConstants.FORCE_PERSIST]) { Persist(false, null); } _inLoadingProcess = false; if (_watchChange && ConfigSection != null) { ConfigSection.StartWatching(); } ChoConfigurationObjectErrorManagerService.ResetObjectErrors(ConfigObject); _firstTime = false; } } } } } }