/// <devdoc>
 ///    <para>Closes the text writer so that it no longer receives tracing or
 ///       debugging output.</para>
 /// </devdoc>
 public override void Close()
 {
     if (eventLog != null)
     {
         eventLog.Close();
     }
 }
        private void DebugWriteLine(EventLogEntryType type, string message)
        {
            _log = new EventLog();
            _log.Source = "ApplicationLog";
            
            _log.WriteEntry(message, type);

            _log.Close();
        }
Ejemplo n.º 3
0
 private static void CloseEventLog(EventLog log)
 {
     try
     {
         log.Close();
     }
     catch (Win32Exception we)
     {
         Console.WriteLine("Error closing event log: " + we.ToString());
     }
 }
Ejemplo n.º 4
0
        public static void SqlExceptionHandling(SqlException sqlex, string strModule, string strMethod, string strMsg)
        {
            EventLog objEventLog = new EventLog();

            string strApplicationName = "SLDDBLog";
            objEventLog.Source = strApplicationName;

            objEventLog.Log = strApplicationName;
            objEventLog.WriteEntry(Environment.NewLine + "Date : " + DateTime.Now + Environment.NewLine + "Module Name : " + strModule + Environment.NewLine + "Method Name : " + strMethod + Environment.NewLine + "Exception Number : " + sqlex.ErrorCode + Environment.NewLine + "Exception Message : " + sqlex.Message + Environment.NewLine + "Additional Information : " + strMsg, EventLogEntryType.Error);
            objEventLog.Close();
            objEventLog.Dispose();
        }
Ejemplo n.º 5
0
 public static void Log(Exception ex)
 {
     var log = new EventLog
     {
         Source = "Xuat_Nhap_Excel/BizService"
     };
     log.WriteEntry(string.Concat(new object[] { ex.Message, Environment.NewLine,
                                                 ex.Source, Environment.NewLine,
                                                 ex.StackTrace,
                                                 ex.TargetSite,
                                                 ex.InnerException }), EventLogEntryType.Error, 100);
     log.Close();
 }
Ejemplo n.º 6
0
 private void Log(string message, int eventId, EventLogEntryType type)
 {
     try
     {
         InitSource();
         EventLog ev = new EventLog(LogName, Environment.MachineName, Source);
         ev.WriteEntry(message, type, eventId);
         ev.Close();
     }
     catch
     {
     }
 }
Ejemplo n.º 7
0
        public void WriteEventLogEntry(string message)
        {
            System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();

            if (!System.Diagnostics.EventLog.SourceExists("SampleApplication"))
            {
                System.Diagnostics.EventLog.CreateEventSource("SampleApplication", "Application");
            }
            eventLog.Source = "SampleApplication";
            int eventID = 8;

            eventLog.WriteEntry(message, System.Diagnostics.EventLogEntryType.Error, eventID);
            eventLog.Close();
        }
        /// <summary>
        /// Called when [log].
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="message">The message.</param>
        public static void OnLog(EventLogEntryType type, string message)
        {
            LogHandler handler = Log;
            if (handler != null) handler(type, "(T"+ Thread.CurrentThread.ManagedThreadId +") " + message);
            if (type == EventLogEntryType.Information) return;

            try
            {
                var log = new EventLog { Log = "Application", Source = "TS3-Bot" };
                log.WriteEntry(message, type);
                log.Close();
            }
            catch
            { }
        }
        /// <summary>
        ///Write Event
        /// </summary>
        ///<param name="pEventMessage"></param>
        private void WriteEventLogEntry(string pEventMessage)
        {
            // Create an instance of EventLog
            System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();

            // Check if the event source exists. If not create it.
            if (!System.Diagnostics.EventLog.SourceExists(source))
            {
                System.Diagnostics.EventLog.CreateEventSource(source, "Application");
            }

            eventLog.Source = source;
            int eventID = 8;

            eventLog.WriteEntry(pEventMessage, System.Diagnostics.EventLogEntryType.Information, eventID);
            eventLog.Close();
        }
 public static void ErrorLog(string LogStr, EventLogEntryType Type)
 {
     try
     {
         WindowsImpersonationContext wic = WindowsIdentity.Impersonate(IntPtr.Zero);
         var El = new EventLog();
         if (EventLog.SourceExists("CIMBTimeSheet") == false)
             EventLog.CreateEventSource("CIMBTimeSheet", "CIMBTimeSheet");
         El.Source = "CIMBTimeSheet";
         El.WriteEntry(LogStr, Type);
         El.Close();
         wic.Undo();
     }
     catch (Exception Ex87)
     {
         WriteTextLog(Ex87.Message + "\r" + LogStr);
     }
 }
Ejemplo n.º 11
0
 private static void WriteEventLog(string event_source, string content, EventLogEntryType type)
 {
     try
     {
         if (!EventLog.SourceExists(event_source))
         {
             EventLog.CreateEventSource(event_source, event_source);
         }
         using (EventLog elog = new EventLog())
         {
             elog.Log = event_source;
             elog.Source = event_source;
             elog.WriteEntry(content, type);
             elog.Close();
         }
     }
     catch { }
 }
 public static void ErrorLog(string LogStr, EventLogEntryType Type)
 {
     try
     {
         System.Security.Principal.WindowsImpersonationContext wic = WindowsIdentity.Impersonate(IntPtr.Zero);
         var El = new EventLog();
         if (EventLog.SourceExists(ErrorLogname) == false)
             EventLog.CreateEventSource(ErrorLogname, ErrorLogname);
         El.Source = ErrorLogname;
         El.WriteEntry(LogStr, Type);
         El.Close();
         wic.Undo();
     }
     catch (Exception Ex87)
     {
         WriteTextLog(Ex87.Message + "\r" + LogStr);
     }
 }
Ejemplo n.º 13
0
        public static void WriteEventLogEntry(EventLogEntryType entryType, int eventID, string message, Modo MError)
        {
            try
            {
                switch (MError)
                {
                case Modo.service:
                    // Create an instance of EventLog
                    System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();

                    // Check if the event source exists. If not create it.
                    if (System.Diagnostics.EventLog.SourceExists("CIMonitor") == false)
                    {
                        System.Diagnostics.EventLog.CreateEventSource("CIMonitor", "CIMonitor");
                    }

                    // Set the source name for writing log entries.
                    eventLog.Source = "CIMonitor";



                    // Write an entry to the event log.
                    eventLog.WriteEntry(message,
                                        entryType,
                                        eventID);

                    // Close the Event Log
                    eventLog.Close();
                    break;

                case Modo.console:
                    WriteLineText(message, "danger");
                    break;

                default:

                    break;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 14
0
 internal static void WriteEventLog(string content, EventLogEntryType type)
 {
     const string event_source = "Soho.Utility.Logger";
     const string event_name = "Soho.Utility.Logger_Exception";
     try
     {
         if (!EventLog.SourceExists(event_source))
         {
             EventLog.CreateEventSource(event_source, event_name);
         }
         using (EventLog elog = new EventLog())
         {
             elog.Log = event_name;
             elog.Source = event_source;
             elog.WriteEntry(content, type);
             elog.Close();
         }
     }
     catch { }
 }
Ejemplo n.º 15
0
        public static void WriteEventLog(Exception exc, string message = "", string eventLogName = Constants.EventLogName)
        {

            try
            {
                if (EventLog.SourceExists(Constants.EventLogName) == true)
                {
                    EventLog myLog = new EventLog();
                    myLog.Source = Constants.EventLogName;
                    myLog.WriteEntry(string.Format("Dev Message {0} ErrorMessage: {1}  \n\nStackTrace: {2}", message, exc.Message, exc.StackTrace), EventLogEntryType.Error);
                    myLog.Close();
                }


            }
            catch (Exception ex)
            {
            }

        }
        public static void Log(string message, EventLogEntryType eventType, EventID eventID)
        {
            const string applicationName = "CIWaterNetService";
            // Create an instance of EventLog
            EventLog eventLog = new EventLog();

            // Check if the event source exists. If not create it.
            if (!System.Diagnostics.EventLog.SourceExists(applicationName))
            {
                EventLog.CreateEventSource(applicationName, "Application");
            }

            // Set the source name for writing log entries.
            eventLog.Source = applicationName;

            // Write an entry to the event log.
            eventLog.WriteEntry(message, eventType,  (int)eventID);

            // Close the Event Log
            eventLog.Close();
        }
Ejemplo n.º 17
0
        public string ReadEventLog(EventLog eventLog, int logcount = 1000)
        {
            var count = logcount;
            var total = eventLog.Entries.Count - 1;
            var sb = new StringBuilder();

            while (count-- > 0)
            {
                var entry = eventLog.Entries[total--];
                sb.AppendFormat("消息:{0};时间:{1};来源:{2};类型:{3};"
                     , entry.Message
                     , entry.TimeGenerated.ToString("yyyy-MM-dd HH:mm:ss.fff")
                     , entry.Source
                     , entry.EntryType.ToString()
                     );
                sb.AppendLine();

            }
            eventLog.Close();

            return sb.ToString();
        }
Ejemplo n.º 18
0
 public void WriteEvent(string strMessage, EventLogEntryType type)
 {
     if (!EventLog.SourceExists(this._sourece))
     EventLog.CreateEventSource(this._sourece, this._eventName);
       EventLog eventLog = new EventLog();
       eventLog.Log = this._eventName;
       eventLog.Source = this._sourece;
       try
       {
     eventLog.WriteEntry(strMessage, type);
       }
       catch (Exception ex)
       {
     eventLog.Clear();
     this.WriteEvent("日志文件已满,执行清除操作!", EventLogEntryType.Warning);
     eventLog.WriteEntry(strMessage, type);
       }
       finally
       {
     eventLog.Close();
     eventLog.Dispose();
       }
 }
Ejemplo n.º 19
0
        public string viewLog(string log,int maxNum)
        {
            String retVal = "";
            //if(EventLog.SourceExists(log))
            try
            {
                EventLog aLog = new EventLog();
                aLog.Log = log;
                aLog.MachineName = ".";
                //foreach (EventLogEntry entry in aLog.Entries)
                EventLogEntry entry;
                for(int i=aLog.Entries.Count-1;(i>0 && (i > aLog.Entries.Count-1 - maxNum));i--)
                {
                    entry = aLog.Entries[i];
                    retVal += " " + entry.TimeGenerated.ToString().Replace(":","#C#") + ": " + entry.EntryType + " - " + entry.Source + "\n" + entry.Message+"\n";
                }
                aLog.Close();
            }
            catch (Exception e){

            }
            return retVal;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Logs message to Windows Event Log. If bool "isError" passed as true, aborts service.
        /// </summary>
        /// <param name="message">Message that will be written to Event Log</param>
        /// <param name="isError">if true, sets event as error and aborts thread</param>
        public static void LogEvent(string message, bool isError)
        {
            EventLog eventLog = new EventLog();

            // Check if the event source exists. If not create it.
            if (!EventLog.SourceExists("EphonetablesSource"))
            {
                EventLog.CreateEventSource("EphonetablesSource", "EphoneTablesLog");
            }

            // Set the source name for writing log entries.
            eventLog.Source = "EphonetablesSource";

            // Create an event ID to add to the event log
            if (!isError)
            {
                eventLog.WriteEvent(new EventInstance(8, 4, EventLogEntryType.Information), message);
            }
            else
            {
                eventLog.WriteEvent(new EventInstance(8, 4, EventLogEntryType.Error), message);
            }
            eventLog.Close();
        }
Ejemplo n.º 21
0
		public void Log ()
		{
			EventLog eventLog = new EventLog ();
			eventLog.Log = string.Empty;
			Assert.AreEqual (string.Empty, eventLog.Log, "#A1");
			Assert.AreEqual (string.Empty, eventLog.Source, "#A2");
			eventLog.Log = "monologtemp";
			Assert.AreEqual ("monologtemp", eventLog.Log, "#A3");
			Assert.AreEqual (string.Empty, eventLog.Source, "#A4");
			eventLog.Log = string.Empty;
			Assert.AreEqual (string.Empty, eventLog.Log, "#A5");
			Assert.AreEqual (string.Empty, eventLog.Source, "#A6");

			if (EventLog.SourceExists ("monotempsource", "."))
				Assert.Ignore ("Event log source 'monotempsource' should not exist.");

			if (EventLog.Exists ("monologtemp", "."))
				Assert.Ignore ("Event log 'monologtemp' should not exist.");

			if (EventLog.Exists ("shouldnotexist", "."))
				Assert.Ignore ("Event log 'shouldnotexist' should not exist.");

			EventLog.CreateEventSource ("monotempsource", "monologtemp", ".");
			try {
				eventLog.Log = "shouldnotexist";
				eventLog.Source = "monotempsource";
				Assert.AreEqual ("shouldnotexist", eventLog.Log, "#B1");
				eventLog.Log = string.Empty;
				Assert.AreEqual ("monologtemp", eventLog.Log, "#B2");
				eventLog.Source = null;
				Assert.AreEqual ("monologtemp", eventLog.Log, "#B3");
				eventLog.Log = "MONOLOGTEMP";
				Assert.AreEqual ("monologtemp", eventLog.Log, "#B4");
			} finally {
				if (EventLog.Exists ("monologtemp"))
					EventLog.Delete ("monologtemp");
				eventLog.Close ();
			}
		}
Ejemplo n.º 22
0
 private void LogEvent(string sText, eloglevel loglevel)
 {
     EventLogEntryType EventType;
     switch(loglevel)
     {
         case eloglevel.error:
             EventType = EventLogEntryType.Error;
             break;
         case eloglevel.warn:
             EventType = EventLogEntryType.Warning;
             break;
         case eloglevel.info:
             EventType = EventLogEntryType.Information;
             break;
         default:
             EventType = EventLogEntryType.Information;
             break;
     }
     //open and write to event log.
     System.Diagnostics.EventLog oEV = new System.Diagnostics.EventLog();
     oEV.Source = m_ProcessName;
     oEV.WriteEntry (sText, EventType);
     oEV.Close();
 }
Ejemplo n.º 23
0
        // NEOLOGGER CLASS
        public NeoLogger (string[] args) {

            // Parse the Command Line Arguments
            this.parseCommandLine(args);
        
            // Creating the syslogsender object
            this.neolog = new SyslogClient.Client();

            // Setting Parameters
            //neolog.RemoteAddress = ip;
            //neolog.RemotePort = port;
            //neolog.PriorityNumber = priority;
            //neolog.FacilityName = facility;
            //neolog.UseUTF8 = true;
            neolog.SysLogServerIp = ip;
            neolog.Port = port;

            // File Positions Dictionary
            filePositions = new Dictionary<string, long>();

// INPUT ######################################################################

            // Input Stream
            if (readType == 1)
            {
                string line;
                // Read input stream lines
                while ((line = Console.ReadLine()) != null)
                {
                    verifiedSend(line);
                }
            }

            // Single Message
            if (readType == 2)
            {
                send(message);
            }

            // File Input
            if (readType == 3)
            {
                // Read only tail lines ----------------------------------------------------
                if (onlyTail)
                {

                    // Open the file
                    StreamReader filestream = null;
                    filestream = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                    // Got to the End of the file
                    filestream.BaseStream.Seek(0, SeekOrigin.End);
                    // Save position
                    filePositions.Add(file, filestream.BaseStream.Position);
                    filestream.Close();

                    // Create a watcher
                    FileSystemWatcher watcher = new FileSystemWatcher();
                    watcher.Path = Path.GetDirectoryName(file);
                    watcher.Filter = Path.GetFileName(file);
                    watcher.NotifyFilter = NotifyFilters.LastWrite;

                    // Add event handlers.	 
                    watcher.Changed += new FileSystemEventHandler(OnChangedFile);
                    // Start watching
                    watcher.EnableRaisingEvents = true;
                    // watcher.WaitForChanged(WatcherChangeTypes.Changed);

                    // Print hint and wait
                    printHint("Stop sending by pressing 'q'");

                }
                // Read only new lines --------------------------------------------------
                else if (onlyNew)
                {

                    // Generate file name
                    string statFile = Path.GetFileName(file) + ".stat";

                    // If stat file exists and contains a last position
                    long savedPos = getOldFilePosFromStat(statFile);
                    // Check if file has been deleted or shrinked in the meantime
                    bool isNewFile = checkFileNew(savedPos);

                    long lastPos = 0;
                    if (  savedPos > 0 && ! isNewFile ) {
                        lastPos = sendFile(this.file, savedPos);
                    }
                    else
                    {
                        lastPos = sendFile(this.file, 0);
                    }

                    // Save the last file pointer position
                    setFilePosToStat(lastPos, statFile);

                }

                // Just read the file and then exit
                else
                {
                    // Send the whole content
                    sendFile(this.file, 0);

                }
            }

            // Eventlog -------------------------------------------------------
            if (readType == 4)
            {
                try {
                    
                    // Open Eventlog
                    ev = new EventLog(eventlogType, System.Environment.MachineName);
                    int LastLogToShow = ev.Entries.Count;
                    if (LastLogToShow <= 0 && debug && !onlyTail)
                        Console.WriteLine("No Event Logs in the Log :" + eventlogType);

                    if (onlyTail)
                    {
                        // Set pointer pos to current size
                        eventlogPos = ev.Entries.Count;

                        ev.EntryWritten += new EntryWrittenEventHandler(OnEventlogChange);
                        ev.EnableRaisingEvents = true;

                        printHint("Stop sending by pressing 'q'");
                    }
                    else if (onlyNew)
                    {
                        // Generate file name
                        string statFile = eventlogType + ".stat";

                        // If file exists
                        if (File.Exists(statFile))
                        {

                            int oldIndex = getOldEventlogPosFromStat(statFile);
                            print("Stat file found. Event Record Id " + oldIndex + " read");
                            // If Eventlog is empty
                            if (ev.Entries.Count < 1)
                            {
                                print("Wanring: Eventlog is empty! Deleting stat file.");
                                File.Delete(statFile);
                            } else {
                                if (oldIndex < ev.Entries[ev.Entries.Count - 1].Index)
                                {
                                    long lastIndex = sendEventlogFromIndex(oldIndex);
                                    File.WriteAllText(statFile, lastIndex.ToString());
                                    if (lastIndex == 0)
                                    {
                                        send("NeoLogger Wanring - Windows Eventlog rotates to fast! Try increasing the eventlog size");
                                    }
                                }
                            }
                        }
                        else
                        {
                            print("No stat file for this Eventlog found. File will be created. Next time NeoLogger is invoked, only new entries will be sent.");
                            File.WriteAllText(statFile, ev.Entries[ev.Entries.Count-1].Index.ToString());
                        }
                    }
                    else
                    {
                        sendEventlog(0);
                    }
                    ev.Close();
                }
                catch (Exception ex)
                {
                    showErrorAndExit("Eventlog with name " + eventlogType + " not found or not accessible. " + ex.ToString());
                }


            }

            // Directory Watcher ----------------------------------------------
            if (readType == 5)
            {
                // Create a watcher
                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path = dir;
                watcher.Filter = file_filter;
                if (includeSubdirectories)
                {
                    watcher.IncludeSubdirectories = true;
                }
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

                // Add event handlers.	 
                watcher.Changed += new FileSystemEventHandler(OnWatcherChangedFile);
                watcher.Created += new FileSystemEventHandler(OnWatcherChangedFile);
                watcher.Deleted += new FileSystemEventHandler(OnWatcherChangedFile);
                watcher.Renamed += new RenamedEventHandler(OnWatcherRenamed);

                // Start watching
                watcher.EnableRaisingEvents = true;
                // watcher.WaitForChanged(WatcherChangeTypes.Changed);

                // Print hint and wait
                printHint("Stop sending by pressing 'q'");

            }

            // Read Directory -------------------------------------------------
            if (readType == 6)
            {
                if (onlyTail)
                {
                    // Walk the directory and save the last positions of the the filesto the dictionary
                    DirectoryInfo directory = new DirectoryInfo(dir);
                    WalkDirectoryTree(directory);

                    // Create a watcher
                    FileSystemWatcher watcher = new FileSystemWatcher();
                    watcher.Path = dir;
                    watcher.Filter = file_filter;
                    if (includeSubdirectories)
                    {
                        watcher.IncludeSubdirectories = true;
                    }
                    watcher.NotifyFilter = NotifyFilters.LastWrite;

                    // Add event handlers.	 
                    watcher.Changed += new FileSystemEventHandler(OnChangedFile);
                    watcher.Created += new FileSystemEventHandler(OnChangedFile);

                    // Start watching
                    watcher.EnableRaisingEvents = true;
                    // watcher.WaitForChanged(WatcherChangeTypes.Changed);

                    // Print hint and wait
                    printHint("Stop sending by pressing 'q'");
                }
                // Send all files content
                else
                {
                    // Walk the directory and send the file contents
                    DirectoryInfo directory = new DirectoryInfo(dir);
                    WalkDirectoryTree(directory);
                }

            }

            // Close Socket
            neolog.Close();

        }
Ejemplo n.º 24
0
        /// <summary>
        /// Creates a handler object and adds it to the internal list.
        /// </summary>
        /// <param name="sHandlerName">The name of the handler to load.</param>
        private static void LoadHandler(string sHandlerName)
        {
            Debug.WriteLine("Loading handler: " + sHandlerName, "HandlerFactory.LoadHandler");

            try
            {
                HandlerConfig oHandlerConfig = m_oLoggerConfig.Handlers.Find(delegate(HandlerConfig obj) { return obj.Name.Equals(sHandlerName, StringComparison.OrdinalIgnoreCase); });

                if (oHandlerConfig == null)
                {
                    Debug.WriteLine("A handler with the name '" + sHandlerName + "' could not be found. Loading default handler for this handler name.");
                    m_colHanderList.Add(sHandlerName, new WindowsEventHandler());
                    //throw new Exception("The configuration for the handler '" + sHandlerName + "' was not found. Check the 'Handlers' section of loggerconfig.xml and make sure the log handler is registered there.");
                }
                else
                {
                    System.Reflection.Assembly assembly = Assembly.LoadFrom(m_sRootFolder + oHandlerConfig.Assembly);
                    Type t = assembly.GetType(oHandlerConfig.Type);

                    if (t == null)
                        throw new Exception("Unable to load the type '" + oHandlerConfig.Type + "' for the handler '" + sHandlerName + "'. Check the 'Handlers' section of loggerconfig.xml and make sure the correct type is specified in the Type tag.");

                    AHandler oPlugin = (AHandler)Activator.CreateInstance(t);
                    oPlugin.Init(oHandlerConfig);

                    m_colHanderList.Add(sHandlerName, oPlugin);
                }

                //switch (sHandlerName)
                //{
                //    case "FileHandler":
                //    {
                //        //m_colHanderList.Add(sHandlerName, new FileHandler());

                //        System.Reflection.Assembly assembly = Assembly.LoadFrom("Logger.dll");
                //        Type t = assembly.GetType("Utils.Log.Handlers.FileHandler");
                //        AHandler oPlugin = (AHandler)Activator.CreateInstance(t);

                //        HandlerConfig oHandlerConfig = m_oLoggerConfig.Handlers.Find(delegate(HandlerConfig obj) { return obj.Name.Equals(sHandlerName, StringComparison.OrdinalIgnoreCase); });

                //        if (oHandlerConfig != null)
                //            oPlugin.Init(oHandlerConfig);
                //        else
                //            throw new Exception("The configuration for the handler '" + sHandlerName + "' was not found. Check the 'Handlers' section of loggerconfig.xml and make sure the log handler is registered there");

                //        m_colHanderList.Add(sHandlerName, oPlugin);

                //        break;
                //    }

                //    case "WindowsEventHandler":
                //        m_colHanderList.Add(sHandlerName, new WindowsEventHandler());
                //        break;

                //    case "SQLDBHandler":
                //        m_colHanderList.Add(sHandlerName, new SQLDBHandler());
                //        break;

                //    default: //WindowsEventHandler
                //        Debug.WriteLine("A handler with the name '" + sHandlerName + "' could not be found. Loading default handler for this handler name.");
                //        m_colHanderList.Add(sHandlerName, new WindowsEventHandler());
                //        break;
                //}
            }
            catch (Exception exp)
            {
                if (!EventLog.SourceExists(m_sAppName))
                    EventLog.CreateEventSource(m_sAppName, "Application");

                EventLog oEventLog = new EventLog();
                oEventLog.Source = m_sAppName;

                oEventLog.WriteEntry("Error loading handler: " + exp.Message, EventLogEntryType.Error, 0);

                if (exp.InnerException != null)
                    oEventLog.WriteEntry("Error loading handler (inner exception):" + exp.InnerException.Message, EventLogEntryType.Error, 0);

                //while (exp.InnerException != null)
                //{
                //    exp = exp.InnerException;
                //    oEventLog.WriteEntry("Error loading handler (inner exception):" + exp.Message, EventLogEntryType.Error, 0);
                //}

                oEventLog.Close();
            }
        }
Ejemplo n.º 25
0
        public static void Delete(string logName, string machineName)
        {
            if (!SyntaxCheck.CheckMachineName(machineName))
            {
                throw new ArgumentException(SR.GetString("InvalidParameterFormat", new object[] { "machineName" }));
            }
            if ((logName == null) || (logName.Length == 0))
            {
                throw new ArgumentException(SR.GetString("NoLogName"));
            }
            if (!ValidLogName(logName, false))
            {
                throw new InvalidOperationException(SR.GetString("BadLogName"));
            }
            new EventLogPermission(EventLogPermissionAccess.Administer, machineName).Demand();
            SharedUtils.CheckEnvironment();
            _UnsafeGetAssertPermSet().Assert();
            RegistryKey eventLogRegKey = null;
            Mutex       mutex          = null;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                SharedUtils.EnterMutex("netfxeventlog.1.0", ref mutex);
                try
                {
                    eventLogRegKey = GetEventLogRegKey(machineName, true);
                    if (eventLogRegKey == null)
                    {
                        throw new InvalidOperationException(SR.GetString("RegKeyNoAccess", new object[] { @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog", machineName }));
                    }
                    using (RegistryKey key2 = eventLogRegKey.OpenSubKey(logName))
                    {
                        if (key2 == null)
                        {
                            throw new InvalidOperationException(SR.GetString("MissingLog", new object[] { logName, machineName }));
                        }
                        EventLog log = new EventLog(logName, machineName);
                        try
                        {
                            log.Clear();
                        }
                        finally
                        {
                            log.Close();
                        }
                        string path = null;
                        try
                        {
                            path = (string)key2.GetValue("File");
                        }
                        catch
                        {
                        }
                        if (path != null)
                        {
                            try
                            {
                                File.Delete(path);
                            }
                            catch
                            {
                            }
                        }
                    }
                    eventLogRegKey.DeleteSubKeyTree(logName);
                }
                finally
                {
                    if (eventLogRegKey != null)
                    {
                        eventLogRegKey.Close();
                    }
                    CodeAccessPermission.RevertAssert();
                }
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                }
            }
        }
Ejemplo n.º 26
0
		public void Constructor4_Log_Empty ()
		{
			if (EventLogImplType == NULL_IMPL)
				// test cannot pass with NULL implementation
				return;

			if (EventLog.SourceExists ("monotempsource", "."))
				Assert.Ignore ("Event log source 'monotempsource' should not exist.");

			bool applicationLogExists = EventLog.Exists ("Application");
			try {
				EventLog eventLog = new EventLog (string.Empty, ".", "monotempsource");
				Assert.IsFalse (eventLog.EnableRaisingEvents, "#A1");
				Assert.IsNotNull (eventLog.Entries, "#A2");
				try {
					eventLog.Entries.GetEnumerator ().MoveNext ();
					Assert.Fail ("#A3a");
				} catch (ArgumentException ex) {
					// Log property is not set (zero-length string)
					Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A3b");
					Assert.IsNotNull (ex.Message, "#A3c");
					Assert.IsNull (ex.InnerException, "#A3d");
					Assert.IsNull (ex.ParamName, "#A3e");
				}
				Assert.IsNotNull (eventLog.Log, "#A4");
				Assert.AreEqual (string.Empty, eventLog.Log, "#A5");
#if NET_2_0
				try {
					string displayName = eventLog.LogDisplayName;
					Assert.Fail ("#A6a: " + displayName);
				} catch (InvalidOperationException ex) {
					// Event log names must consist of printable characters and
					// cannot contain \, *, ?, or spaces
					Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A6b");
					Assert.IsNotNull (ex.Message, "#A6c");
					Assert.IsNull (ex.InnerException, "#A6d");
				}
#else
				Assert.IsNotNull (eventLog.LogDisplayName, "#A6a");
				Assert.AreEqual (string.Empty, eventLog.LogDisplayName, "#A6b");
#endif
				Assert.IsNotNull (eventLog.MachineName, "#A7");
				Assert.AreEqual (".", eventLog.MachineName, "#A8");
				Assert.IsNotNull (eventLog.Source, "#A9");
				Assert.AreEqual ("monotempsource", eventLog.Source, "#A10");
				eventLog.Close ();
			} finally {
				if (!applicationLogExists) {
					if (EventLog.Exists ("Application"))
						EventLog.Delete ("Application");
				} else {
					if (EventLog.SourceExists ("monotempsource", "."))
						EventLog.DeleteEventSource ("monotempsource", ".");
				}
			}
		}
Ejemplo n.º 27
0
 public override void Close() => EventLog?.Close();
Ejemplo n.º 28
0
		/// <summary>
		/// Translates Syslog messages to Eventlog messages
		/// Using Pri part as source, and log them to Windows EventLog
		/// </summary>
		/// <param name="endPoint">IP/port number from datagram sender</param>
		/// <param name="strReceived">Syslog message</param>
		private void Log(EndPoint endPoint, string strReceived)
		{
			Pri pri = new Pri(m_regex.Match(strReceived).Groups[1].Value);

			EventLogEntryType eventLogEntryType = Severity2EventLogEntryType(pri.Severity);

			string strMessage = string.Format("{0} : {1}", endPoint, m_regex.Replace(strReceived, evaluator));

			EventLog myLog = new EventLog(m_EventLog);
			myLog.Source = pri.ToString();
			myLog.WriteEntry(strMessage, eventLogEntryType);
			myLog.Close();
			myLog.Dispose();
		}
Ejemplo n.º 29
0
        /// <summary>
        /// Writes internal exceptions to the windows event log.
        /// If this throws and exception it will be rethrown to the
        /// caller.
        /// </summary>
        /// <param name="sMessage">The message</param>
        /// <param name="oException">The exception</param>
        private void ExceptionWriter(string sMessage, Exception oException)
        {
            try
            {
                if (!EventLog.SourceExists(m_sAppSourceName))
                {
                    EventLog.CreateEventSource(m_sAppSourceName, "Application");
                }

                EventLog oEventLog = new EventLog();

                oEventLog.Source = m_sAppSourceName;
                oEventLog.WriteEntry(sMessage + "\r\nLogger will now stop logging events!.\r\nThe error message was: " + oException.Message + "\r\nStacktrace:\r\n" + oException.StackTrace, EventLogEntryType.Error, 0);

                oEventLog.Close();
            }
            catch (Exception exp)
            {
                Debug.WriteLine("A fatal exception occured in Logger.ExceptionWriter: " + exp.Message + "\r\nStacktrace:\r\n" + exp.StackTrace, "Logger");
                throw new Exception("A fatal exception occured in Logger.ExceptionWriter: " + exp.Message + "\r\nCheck inner exception for information regarding the source of this error.", exp);
            }
            finally
            {
                if (m_oTimer != null)
                    m_oTimer.Dispose();

                m_qEvents = null;
            }
        }
 public override void Close()
 {
     event_log.Close();
 }
Ejemplo n.º 31
0
		public void Constructor3_Log_Empty ()
		{
			if (EventLogImplType == NULL_IMPL)
				// test cannot pass with NULL implementation
				Assert.Ignore ("No EventLogImplType.");

			EventLog eventLog = new EventLog (string.Empty, ".");
			Assert.IsFalse (eventLog.EnableRaisingEvents, "#A1");
			Assert.IsNotNull (eventLog.Entries, "#A2");
			try {
				eventLog.Entries.GetEnumerator ().MoveNext ();
				Assert.Fail ("#A3a");
			} catch (ArgumentException ex) {
				// Log property is not set (zero-length string)
				Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A3b");
				Assert.IsNotNull (ex.Message, "#A3c");
				Assert.IsNull (ex.InnerException, "#A3d");
				Assert.IsNull (ex.ParamName, "#A3e");
			}
			Assert.IsNotNull (eventLog.Log, "#A4");
			Assert.AreEqual (string.Empty, eventLog.Log, "#A5");
			try {
				string displayName = eventLog.LogDisplayName;
				Assert.Fail ("#A6a: " + displayName);
			} catch (InvalidOperationException ex) {
				// Event log names must consist of printable characters and
				// cannot contain \, *, ?, or spaces
				Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A6b");
				Assert.IsNotNull (ex.Message, "#A6c");
				Assert.IsNull (ex.InnerException, "#A6d");
			}
			Assert.IsNotNull (eventLog.MachineName, "#A7");
			Assert.AreEqual (".", eventLog.MachineName, "#A8");
			Assert.IsNotNull (eventLog.Source, "#A9");
			Assert.AreEqual (string.Empty, eventLog.Source, "#A10");
			eventLog.Close ();
		}
Ejemplo n.º 32
0
        private void AddWindowsEventLog(string message, EventLogEntryType logType = EventLogEntryType.Information, string moduleName = "", int codeErreur = 0, bool fromFileLogEvent = false)
        {
            EventLog evLog = new EventLog(Const.WINDOWS_LOG_NAME);

            message = string.Concat(message, "\r\n", "Module : ", moduleName);
            evLog.Source = Const.DEFAULT_APPLICATION_NAME;

            InitWindowsEventLog();

            try
            {
                evLog.WriteEntry(message, logType, codeErreur);
            }
            catch (Exception ex)
            {
                if (!fromFileLogEvent)
                {
                    AddFileEventLog("Impossible d'écrire dans le journal de log " + Log.Const.WINDOWS_LOG_NAME + ".\r\nLe journal doit être créé préalablement avec un compte Administrateur.\r\nMessage :\r\n" + message + "\r\nException : " + ex.Message, logType, moduleName, codeErreur, true);
                }
            }
            finally
            {
                evLog.Close();
            }
        }
Ejemplo n.º 33
0
		public void Constructor1 ()
		{
			if (EventLogImplType == NULL_IMPL)
				// test cannot pass with NULL implementation
				return;

			EventLog eventLog = new EventLog ();
			Assert.IsFalse (eventLog.EnableRaisingEvents, "#1");
			Assert.IsNotNull (eventLog.Entries, "#2");
			try {
				eventLog.Entries.GetEnumerator ().MoveNext ();
				Assert.Fail ("#3a");
			} catch (ArgumentException ex) {
				// Log property is not set (zero-length string)
				Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#3b");
				Assert.IsNotNull (ex.Message, "#3c");
				Assert.IsNull (ex.InnerException, "#3d");
				Assert.IsNull (ex.ParamName, "#3e");
			}
			Assert.IsNotNull (eventLog.Log, "#4");
			Assert.AreEqual (string.Empty, eventLog.Log, "#5");
#if NET_2_0
			try {
				string displayName = eventLog.LogDisplayName;
				Assert.Fail ("#6a: " + displayName);
			} catch (InvalidOperationException ex) {
				// Event log names must consist of printable characters and
				// cannot contain \, *, ?, or spaces
				Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#6b");
				Assert.IsNotNull (ex.Message, "#6c");
				Assert.IsNull (ex.InnerException, "#6d");
			}
#else
			Assert.IsNotNull (eventLog.LogDisplayName, "#6a");
			Assert.AreEqual (string.Empty, eventLog.LogDisplayName, "#6b");
#endif
			Assert.IsNotNull (eventLog.MachineName, "#7");
			Assert.AreEqual (".", eventLog.MachineName, "#8");
			Assert.IsNotNull (eventLog.Source, "#9");
			Assert.AreEqual (string.Empty, eventLog.Source, "#10");
			eventLog.Close ();
		}
Ejemplo n.º 34
0
		/// <summary>
		/// Worker thread, setting up an listening socket for UDP datagrams
		/// </summary>
		private void Worker()
		{
			Properties.Settings settings = new Properties.Settings();

			m_EventLog = settings.EventLog;

			IPAddress ipAddress = IPAddress.Any;
			if(settings.Address!="*")
				ipAddress = IPAddress.Parse(settings.Address);

			IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, settings.Port);

			m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			m_socket.Bind(ipEndPoint);


			// Recycling vars , i love it.
			EndPoint endPoint = ipEndPoint;

			// http://www.ietf.org/rfc/rfc3164.txt
			// 4.1 syslog Message Parts
			// The total length of the packet MUST be 1024 bytes or less.
			byte[] buffer = new byte[1024];

			while (m_running)
			{
				try
				{
					int intReceived = m_socket.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endPoint);
					string strReceived = Encoding.ASCII.GetString(buffer, 0, intReceived);
					Log(endPoint, strReceived);
				}
				catch (Exception exception)
				{
					EventLog myLog = new EventLog();
					myLog.Source = settings.ServiceName;
					if (!m_running)
						myLog.WriteEntry("Stopping...", EventLogEntryType.Information);
					else
						myLog.WriteEntry(exception.Message, EventLogEntryType.Error);
					myLog.Close();
					myLog.Dispose();
				}
			}
		}
Ejemplo n.º 35
0
		public void Constructor4_Log_DoesNotExist ()
		{
			if (EventLogImplType == NULL_IMPL)
				// test cannot pass with NULL implementation
				return;

			if (EventLog.Exists ("monologtemp", "."))
				Assert.Ignore ("Event log 'monologtemp' should not exist.");

			EventLog eventLog = new EventLog ("monologtemp", ".", "monotempsource");
			Assert.IsFalse (eventLog.EnableRaisingEvents, "#B1");
			Assert.IsNotNull (eventLog.Entries, "#B2");
			try {
				eventLog.Entries.GetEnumerator ().MoveNext ();
				Assert.Fail ("#B3a");
			} catch (InvalidOperationException ex) {
				// The event log 'monologtemp' on computer '.' does not exist
				Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B3b");
				Assert.IsNotNull (ex.Message, "#B3c");
				Assert.IsTrue (ex.Message.IndexOf ("'monologtemp'") != -1, "#B3d");
				Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#B3e");
				Assert.IsNull (ex.InnerException, "#B3f");
			}
			Assert.IsNotNull (eventLog.Log, "#B4");
			Assert.AreEqual ("monologtemp", eventLog.Log, "#B5");
			try {
				string displayName = eventLog.LogDisplayName;
				Assert.Fail ("#B6a: " + displayName);
			} catch (InvalidOperationException ex) {
				// Cannot find Log monologtemp on computer .
				Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B6b");
				Assert.IsNotNull (ex.Message, "#B6c");
				Assert.IsTrue (ex.Message.IndexOf ("monologtemp") != -1, "#B6d");
				Assert.IsTrue (ex.Message.IndexOf (".") != -1, "#B6e");
				Assert.IsNull (ex.InnerException, "#B6f");
			}
			Assert.IsNotNull (eventLog.MachineName, "#B7");
			Assert.AreEqual (".", eventLog.MachineName, "#B8");
			Assert.IsNotNull (eventLog.Source, "#B9");
			Assert.AreEqual ("monotempsource", eventLog.Source, "#B10");
			eventLog.Close ();
		}
Ejemplo n.º 36
0
		/// <summary>
		/// This method will do the actual writing of the event to the event log.
		/// </summary>
		/// <param name="eventId">ID of the Event Log entry</param>
		/// <param name="categoryId">Category of the Event Log entry</param>
		/// <param name="eventLogType">Type of Event Log entry</param>
		/// <param name="description">The log entry to be written</param>
		/// <param name="rawData">Any extra data to be written</param>
		/// <param name="logName">Name of the Event Log</param>
		/// <param name="machineName">Name of the computer where the Event Log is stored.</param>
		/// <param name="applicationName">The name of the application source</param>
		private static void WriteLog(int eventId, short categoryId, EventLogEntryType eventLogType, string description, byte[] rawData, string logName, string machineName, string applicationName)
		{
			//  Check the parameters passed in.  They should be ok as this method is private, but you never know.
			Debug.Assert(eventId > 0, "The Event ID has a value of zero!");
			if (eventId == 0)
			{
				throw new ArgumentException(SmartResourceManager.GetString("SEL_001", "Workshare.Common.Exceptions.Resource", Assembly.GetAssembly(typeof(SmartEventLog)), System.Threading.Thread.CurrentThread.CurrentCulture));
			}
			Debug.Assert(categoryId > 0, "The Category ID has a value of zero!");
			if (categoryId == 0)
			{
				throw new ArgumentException(SmartResourceManager.GetString("SEL_002", "Workshare.Common.Exceptions.Resource", Assembly.GetAssembly(typeof(SmartEventLog)), System.Threading.Thread.CurrentThread.CurrentCulture));
			}
			Debug.Assert(logName.Trim().Length > 0, "Log Name has not been initialised!");
			if (logName.Trim().Length == 0)
			{
				throw new ArgumentException(SmartResourceManager.GetString("SEL_003", "Workshare.Common.Exceptions.Resource", Assembly.GetAssembly(typeof(SmartEventLog)), System.Threading.Thread.CurrentThread.CurrentCulture));
			}
			// If the computer name is empty then we will populate with a .
			if (machineName.Trim().Length == 0)
			{
				machineName = ".";
			}
			// Check the length of the description.
			if (description.Trim().Length > 8096)
			{
				// Will only use the first 8kb
				description = description.Substring(0, 8095);
			}
			if (description.Trim().Length == 0)
			{
				throw new ArgumentException(SmartResourceManager.GetString("SEL_004", "Workshare.Common.Exceptions.Resource", Assembly.GetAssembly(typeof(SmartEventLog)), System.Threading.Thread.CurrentThread.CurrentCulture));
			}
			// If we are here then the parameters are valid.
			try
			{
				EventLog log = new EventLog(logName, machineName, applicationName);
				lock (log)
				{
					// Now write the log.
					// Check to see if any extra data is to be written.
					if (rawData != null && rawData.GetLength(0) > 0)
					{
						log.WriteEntry(description, eventLogType, eventId, categoryId, rawData);
					}
					else
					{
						log.WriteEntry(description, eventLogType, eventId, categoryId);
					}
					log.Close();
				}
			}
			catch (Win32Exception)
			{
				// More than likely the log is full.
				throw;
			}
		}
        ////////////////////////////////////////////// STATIC METHODS /////////////////////////////////////////////

        internal static void WriteLog(string message)
        {
            using (EventLog eventLog = new EventLog("SenseNet"))
            {
                eventLog.Source = "Portal";
                eventLog.WriteEntry(message, EventLogEntryType.Information);
                eventLog.Close();
            }
        }