public static async void LogMessageToFile(string message, LoggingLevel level)
        {
            // Initialization
            if (fileLoggingSession == null)
            {
                fileLoggingSession = new FileLoggingSession("NewTestamentLogSession");
            }
            using (var loggingChannel = new LoggingChannel(
                       "NewTestamentLogSession",
                       new LoggingChannelOptions(new Guid("2e0582f3-d1b6-516a-00e3-9fd79ef95200")))) // Join a provider group
            {
                // The Id is generated by hashing the string "SampleProvider".
                // channel.Id == eff1e128-4903-5093-096a-bdc29b38456f
                fileLoggingSession.AddLoggingChannel(loggingChannel);
                // Log messages
                loggingChannel.LogMessage(message, level);
            }
            var file = await fileLoggingSession.CloseAndSaveToFileAsync();

            StorageFolder sampleAppDefinedLogFolder =
                await ApplicationData.Current.LocalFolder.CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists);

            string newLogFileName = "Log1-" + TimeStamp.Now() + ".etl";
            await file.MoveAsync(sampleAppDefinedLogFolder, newLogFileName);
        }
示例#2
0
    /// <summary>
    /// Call this before logging starts.
    /// </summary>
    /// <param name="rootFolderPattern">Should match the top folder name(s) within the source control repository, e.g. @"\MobileRealtimePush\MobileRealtimePush\". Any folders before the first match of this pattern are omitted from the logged source file paths</param>
    public static void Init(string rootFolderPattern = null)
    {
        XLog.rootFolderPattern = rootFolderPattern;
#if WINDOWS_UWP
        loggingChannel = new LoggingChannel("XLog provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
#endif
    }
        //
        // The Run method is the entry point of a background task.
        //
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            if (lc == null)
            {
                lc = new LoggingChannel("Tile", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
            }

            lc.LogMessage("Run entry");
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");

            PlaySound();

            //
            // Associate a cancellation handler with the background task.
            //
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            //
            // Get the deferral object from the task instance, and take a reference to the taskInstance;
            //
            //_deferral = taskInstance.GetDeferral();
            _taskInstance = taskInstance;

            //_periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
        }
示例#4
0
        /// <summary>
        /// Adds a logging channel to the current logging session.
        /// </summary>
        /// <param name="name">The name of the logging channel.</param>
        /// <returns>a new logging channel.</returns>
        public static LoggingChannel AddLoggingChannel(string name)
        {
            var loggingChannel = new LoggingChannel(string.IsNullOrWhiteSpace(name) ? "VLC" : name, null);

            LoggingSession.AddLoggingChannel(loggingChannel);
            return(loggingChannel);
        }
示例#5
0
        public Log()
        {
            Channel = new LoggingChannel("DroneLogChannel", new LoggingChannelOptions());
            Session = new FileLoggingSession("Drone Session");

            Session.AddLoggingChannel(Channel, LoggingLevel.Information);
        }
示例#6
0
 // Make the object construction private to allow singleton access to this class
 private AppLifecycleLogger()
 {
     m_appLifecycleProvider = new LoggingChannel(
         "Microsoft.Windows.AppLifeCycle",
         new LoggingChannelOptions(new Guid(0x4f50731a, 0x89cf, 0x4782, 0xb3, 0xe0, 0xdc, 0xe8, 0xc9, 0x4, 0x76, 0xba)),
         new Guid(0xef00584a, 0x2655, 0x462c, 0xbc, 0x24, 0xe7, 0xde, 0x63, 0xe, 0x7f, 0xbf));
 }
示例#7
0
        /// <summary>
        /// </summary>
        private Logs()
        {
            Create();
            //Creating channel for logging in Holo Web portail
            loggingChannel = new LoggingChannel(Application.productName, null, new Guid());
            fls            = new FileLoggingSession(Application.productName);
            fls.AddLoggingChannel(loggingChannel);

            WritingTask = Task.Run(async() => {
                //While logs instance exist, wait for a task for writing
                while (Writing)
                {
                    if (queue.Count > 0)
                    {
                        queue.Dequeue()();
                    }
                    else
                    {
                        await Task.Delay(1000);
                    }
                }
                // Clearing the queue before disposing
                while (queue.Count < 0)
                {
                    queue.Dequeue()();
                }
            });
        }
        /// <summary>
        /// Logs to <see cref="Constants.ETWChannelName"/> and either to <see cref="Debug.WriteLine"/> or <see cref="CustomLog"/>
        /// </summary>
        public static void Log(string message, LoggingLevel level)
        {
            /*
             *  You can collect the events generated by this method with xperf or another
             *  ETL controller tool. To collect these events in an ETL file:
             *
             *  xperf -start MySession -f MyFile.etl -on Constants.ETWGuid
             *  (call LogError())
             *  xperf -stop MySession
             *
             *  After collecting the ETL file, you can decode the trace using xperf, wpa,
             *  or tracerpt. For example, to decode MyFile.etl with tracerpt:
             *
             *  tracerpt MyFile.etl
             *  (generates dumpfile.xml)
             */

            using (var channel = new LoggingChannel(Constants.ETWChannelName, null /*default options*/, new Guid(Constants.ETWGuid)))
            {
                channel.LogMessage(message, level);
            }

            if (CustomLog != null)
            {
                CustomLog(message, level);
            }
            else
            {
                Debug.WriteLine("[" + Constants.ETWChannelName + "]    [" + level.ToString() + "]    " + message);
            }
        }
示例#9
0
        /*************************
        * OutputWebPages checks whether the data coming in is "Request=Feedback" if it is then
        * only the feedback variable is sent back prefixed with "Result: ". Thus the jquery
        * in HTML webpage can look for this keyword at the begining of the text to take any
        * action.
        * If Feedback info is not requested, a webpage is constructed and sent. Note that the
        * Header and body tags are added to the webpage while the contents are read from
        * respective files. A line for providing the log is added at the end with an ID of retVal for
        * calling theme benefit. The log line provides decoded input passed by webpage
        * ***********************/
        private async void OutputWebPage(StreamSocketListenerConnectionReceivedEventArgs args, string inputString)
        {
            bAction = inputString.Contains("Action");

            //Use the next two lines for event logging
            //lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
            //lc.LogMessage(inputString.ToString());

            string data = string.IsNullOrWhiteSpace(feedBack) ? "None" : feedBack;

            try
            {
                using (IOutputStream output = args.Socket.OutputStream)
                {
                    using (Stream response = output.AsStreamForWrite())
                    {
                        if (bAction)
                        {
                            //data = "Results: " + feedBack;
                            //data = DateTime.Now.TimeOfDay.ToString();
                            byte[] fbArray = Encoding.UTF8.GetBytes(data);
                            await response.WriteAsync(fbArray, 0, fbArray.Length);

                            await response.FlushAsync();

                            //Use the next two lines for event logging
                            //lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
                            //lc.LogMessage(feedBack);
                        }
                        else
                        {
                            byte[] bodyArray = Encoding.UTF8.GetBytes(
                                $"<!DOCTYPE html>\n<html>\n<head>{headerFile}<style>{cssFile}</style>\n</head>\n<body>{bodyFile}<p>Feedback Received: <span id=\"retVal\">{data}</span></p>\n</body>\n</html>");

                            var bodyStream = new MemoryStream(bodyArray);

                            var header = "HTTP/1.1 200 OK\r\n" +
                                         $"Content-Length: {bodyStream.Length}\r\n" +
                                         "Connection: close\r\n\r\n";

                            byte[] headerArray = Encoding.UTF8.GetBytes(header);
                            await response.WriteAsync(headerArray, 0, headerArray.Length);

                            await bodyStream.CopyToAsync(response);

                            await response.FlushAsync();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception Occured: {0}", ex);
                //Uncomment next two lines for logging the exception errors
                lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
                lc.LogMessage("Exception at Output Page: " + ex);
                bMsg = false;
            }
        }
示例#10
0
        private void InitiateLogger()
        {
            _filelogSession = new FileLoggingSession("DDPaiDashSession");
            _logChannel     = new LoggingChannel("DDPaiDashChannel");
            _filelogSession.AddLoggingChannel(_logChannel);

            CoreApplication.UnhandledErrorDetected += CoreApplication_UnhandledErrorDetected;
        }
示例#11
0
        public MainPage()
        {
            InitializeComponent();

            LoggingChannel lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));

            lc.LogMessage("I made a message!");
        }
        /// <summary>
        /// Construct a LoggingChannel with the Windows 8.1 constructor, then
        /// use the LoggingChannel for the scenario.
        /// </summary>
        public void LogWithWin81Constructor()
        {
            /*
            You can collect the events generated by this method with xperf or another
            ETL controller tool. To collect these events in an ETL file:

            xperf -start MySession -f MyFile.etl -on 4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a
            (run the sample and click the "Windows 8.1 behavior" button)
            xperf -stop MySession

            After collecting the ETL file, you can decode the trace using xperf, wpa,
            or tracerpt. For example, to decode MyFile.etl with tracerpt:

            tracerpt MyFile.etl
            (generates dumpfile.xml)

            Note that decoding TraceLogging events requires Windows 10. Earlier versions
            of Windows can only reliably decode the simple (manifest-based) events.
            */

            /*
            If a LoggingChannel is created using the 1-parameter constructor, it
            will use Windows 8.1 semantics:

            - The channel's ETW Id is always "4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a".
            - The channel's ETW Name is is always
              "Microsoft-Windows-Diagnostics-LoggingChannel".
            - A LoggingChannelName field containing the Channel Name is automatically
              added to each event.
            - Simple events will be written using manifested-event encoding.
            
            Note that complex events can be written even when using Windows 8.1 mode.
            Complex events always use TraceLogging encoding.

            The 1-parameter constructor is marked as obsolete to ensure that
            developers are aware of the changes in semantics. The Windows 10 semantics
            are useful because they enable use of the ETW Provider Id for event
            filtering.
            */

            /*
            If a LoggingChannel is used as a local or member variable, it should
            be closed (disposed) when no longer needed. C# will do this automatically
            if you enclose the usage in a using block.
            */

            // The 1-parameter constructor creates a channel with Windows 8.1 semantics.
#pragma warning disable 618 // Disable warning for use of obsolete LoggingChannel constructor.
            using (var channel = new LoggingChannel("SampleProvider"))
            {
                // The Id for a Windows 8.1-mode channel is always the same.
                // channel.Id == 4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a

                this.DemonstrateLogging(channel);
            }
#pragma warning restore 618
        }
示例#13
0
        public async void InitiateLogger()
        {
            LogChannel = new LoggingChannel("OctoCentralChannel");
            LogSession = new LoggingSession("OctoCentral Session");

            LogSession.AddLoggingChannel(LogChannel);

            await RegisterUnhandledErrorHandler();
        }
示例#14
0
 /// <summary>
 /// Initial application - Done once
 /// </summary>
 /// <returns></returns>
 private bool InitApplication(LoggingChannel logging, AzureIoTHubService azureIoTService, GPIOService gpioService)
 {
     //Config
     //var localSettings = ApplicationData.Current.LocalSettings;
     _logging            = logging;
     _azureIoTHubService = azureIoTService;
     _gpioService        = gpioService;
     return(true);
 }
示例#15
0
        public async void InitiateLogger()
        {
            LogChannel = new LoggingChannel("OctoCentralChannel");
            LogSession = new LoggingSession("OctoCentral Session");

            LogSession.AddLoggingChannel(LogChannel);

            await RegisterUnhandledErrorHandler();
        }
示例#16
0
        private Logger()
        {
            session = new LoggingSession("AllJoynVoiceSession");
            channel = new LoggingChannel("AllJoynVoiceChannel", null);

            session.AddLoggingChannel(channel);

            Windows.UI.Xaml.Application.Current.UnhandledException += Current_UnhandledException;
        }
        /// <summary>
        /// Construct a LoggingChannel with the Windows 8.1 constructor, then
        /// use the LoggingChannel for the scenario.
        /// </summary>
        public void LogWithWin81Constructor()
        {
            /*
             * You can collect the events generated by this method with xperf or another
             * ETL controller tool. To collect these events in an ETL file:
             *
             * xperf -start MySession -f MyFile.etl -on 4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a
             * (run the sample and click the "Windows 8.1 behavior" button)
             * xperf -stop MySession
             *
             * After collecting the ETL file, you can decode the trace using xperf, wpa,
             * or tracerpt. For example, to decode MyFile.etl with tracerpt:
             *
             * tracerpt MyFile.etl
             * (generates dumpfile.xml)
             *
             * Note that decoding TraceLogging events requires Windows 10. Earlier versions
             * of Windows can only reliably decode the simple (manifest-based) events.
             */

            /*
             * If a LoggingChannel is created using the 1-parameter constructor, it
             * will use Windows 8.1 semantics:
             *
             * - The channel's ETW Id is always "4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a".
             * - The channel's ETW Name is is always
             * "Microsoft-Windows-Diagnostics-LoggingChannel".
             * - A LoggingChannelName field containing the Channel Name is automatically
             * added to each event.
             * - Simple events will be written using manifested-event encoding.
             *
             * Note that complex events can be written even when using Windows 8.1 mode.
             * Complex events always use TraceLogging encoding.
             *
             * The 1-parameter constructor is marked as obsolete to ensure that
             * developers are aware of the changes in semantics. The Windows 10 semantics
             * are useful because they enable use of the ETW Provider Id for event
             * filtering.
             */

            /*
             * If a LoggingChannel is used as a local or member variable, it should
             * be closed (disposed) when no longer needed. C# will do this automatically
             * if you enclose the usage in a using block.
             */

            // The 1-parameter constructor creates a channel with Windows 8.1 semantics.
#pragma warning disable 618 // Disable warning for use of obsolete LoggingChannel constructor.
            using (var channel = new LoggingChannel("SampleProvider"))
            {
                // The Id for a Windows 8.1-mode channel is always the same.
                // channel.Id == 4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a

                this.DemonstrateLogging(channel);
            }
#pragma warning restore 618
        }
示例#18
0
        public async void InitiateLogger()
        {
            logChannel = new LoggingChannel("MySampleChannel");
            logSession = new LoggingSession("MySample Session");

            logSession.AddLoggingChannel(logChannel);

            await RegisterUnhandledErrorHandler();
        }
示例#19
0
        void IMessageHandler.Initialise(LoggingChannel logging, IMqttClient mqttClient, Rfm9XDevice rfm9XDevice, string platformSpecificConfiguration)
        {
            LoggingFields processInitialiseLoggingFields = new LoggingFields();

            this.Logging     = logging;
            this.MqttClient  = mqttClient;
            this.Rfm9XDevice = rfm9XDevice;
            this.PlatformSpecificConfiguration = platformSpecificConfiguration;
        }
        static LoggingService()
        {
            _LcDebug = new LoggingChannel(
                "QuickbirdUWP_Log",
                new LoggingChannelOptions(new Guid("d3020f82-b5bd-4ead-b739-a2e043d075f3"))
                );

            _Session = new LoggingSession("AppWideSession");
            _Session.AddLoggingChannel(_LcDebug);
        }
示例#21
0
        public LoggingService()
        {
            logChannel = new LoggingChannel(LOG_CHANNEL_RESROUCE_NAME, new LoggingChannelOptions());
            logSession = new LoggingSession(LOG_SESSION_RESROUCE_NAME);
            logSession.AddLoggingChannel(logChannel);

            semaphoreLock = new SemaphoreSlim(1);

            CoreApplication.UnhandledErrorDetected           += OnUnhandledErrorDetected;
            PrismUnityApplication.Current.UnhandledException += OnUnhandledException;
        }
示例#22
0
 /// <summary>
 /// Removes the specified logging channel from the current logging session.
 /// </summary>
 /// <param name="loggingChannel">The logging channel to remove.</param>
 public static void RemoveLoggingChannel(LoggingChannel loggingChannel)
 {
     if (loggingChannel != null)
     {
         try
         {
             LoggingSession.RemoveLoggingChannel(loggingChannel);
             loggingChannel.Dispose();
         }
         catch (Exception) { }
     }
 }
示例#23
0
        /******************************************
        * This procedure listens for messages arriving to socket 8090. This information will be
        * built to string. It will then extract the data from the received string
        * by calling GetQuery method. The data is properly dispatched to the service connection
        * established / stored by this application.
        * Finally OutputWebpage is called to provide feedback to the webclient.
        * bMsg bool is added to ensure that when multiple messages are received, the messages are discarded.
        * This is required. Without this, the Webservice crashes after some time.
        ******************************************/
        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            if (!bMsg)
            {
                bMsg = true;
                StringBuilder request = new StringBuilder();
                try
                {
                    using (IInputStream input = args.Socket.InputStream)
                    {
                        byte[]  data     = new byte[BUFFERSIZE];
                        IBuffer buffer   = data.AsBuffer();
                        uint    dataRead = BUFFERSIZE;
                        while (dataRead == BUFFERSIZE)
                        {
                            await input.ReadAsync(buffer, BUFFERSIZE, InputStreamOptions.Partial);

                            request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                            dataRead = buffer.Length;
                        }
                    }

                    string inputString = GetQuery(request);

                    //If you are running as a background webserver serviceConnection will be null
                    //Dispatch the message to the service connection.
                    if (serviceConnection != null)
                    {
                        await serviceConnection.SendMessageAsync(new ValueSet { new KeyValuePair <string, object>("Query", inputString) });
                    }

                    OutputWebPage(args, inputString);
                }
                catch (Exception Ex)
                {
                    Debug.WriteLine("Exception occurred: {0}", Ex);
                    //Uncomment next two lines for logging the exception errors
                    lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
                    lc.LogMessage("Exception at Input String: " + Ex);
                    bMsg = false;
                }
                bMsg = false;
            }
            //Uncomment the else statement if you want to use debugging

            /*
             * else
             * {
             *  lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
             *  lc.LogMessage("Multiple messages received");
             * }
             */
        }
示例#24
0
        /// <summary>
        /// Disallow creation of instances beyond the one instance for the process.
        /// The one instance is accessible via the Instance property (see below).
        /// </summary>
        private LoggingDispatcher()
        {
            LogFileGeneratedCount = 0;

            channel = new LoggingChannel(DEFAULT_CHANNEL_NAME, null);

            channel.LoggingEnabled += OnChannelLoggingEnabled;

            // If the app is being launched (not resumed), the
            // following call will activate logging if it had been
            // activated during the last suspend.
            ResumeLoggingIfApplicable();
        }
示例#25
0
        private FileEventLog()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            channel = new LoggingChannel(DEFAULT_CHANNEL_NAME);
#pragma warning restore CS0618 // Type or member is obsolete

            channel.LoggingEnabled += OnChannelLoggingEnabled;

            App.Current.Suspending += OnAppSuspending;
            App.Current.Resuming   += OnAppResuming;

            ResumeLoggingIfApplicable();
        }
示例#26
0
        public void 順序保証()
        {
            const int NumExecuteLoop = 30;

            var c = new Channel <Message>(InvocationMode.Parallel);

            var list = new List <int>();

            Func <Holder <Message>, int, Task> f = async(m, offset) =>
            {
                await Task.Delay(1);

                var value = ((MessageB)m.Value).Value;
                lock (list)
                    list.Add(3 * value + offset);
            };

            ISender <Holder <Message> > s = new LoggingChannel <Holder <Message> >(c,
                                                                                   (m, ct) => f(m, 0), // A
                                                                                   (m, ct) => f(m, 2), // B
                                                                                   InvocationMode.Parallel);

            s.Subscribe((m, ct) => f(m, 1)); // C
            s.Subscribe((m, ct) => f(m, 1));
            s.Subscribe((m, ct) => f(m, 1));

            //↑ メッセージが来るたびに、A, C, C, C, B の順で動くはず。C 3つの順序については保証なし。

            Func <CancellableReceiver <Message>, Task> executor = async r =>
            {
                await Task.Run(() => { }).ConfigureAwait(false);

                for (int i = 0; i < NumExecuteLoop; i++)
                {
                    await Task.Delay(1);

                    var res = (await r.SendAsync(new MessageB(0, i))).GetResponse();
                }
            };

            c.Execute(executor, CancellationToken.None);
            c.Completed.Wait();

            Assert.AreEqual(5 * NumExecuteLoop, list.Count);
            Assert.IsTrue(list.SequenceEqual(list.OrderBy(x => x)));
            Assert.AreEqual(NumExecuteLoop, list.Count(x => (x % 3) == 0));
            Assert.AreEqual(3 * NumExecuteLoop, list.Count(x => (x % 3) == 1));
            Assert.AreEqual(NumExecuteLoop, list.Count(x => (x % 3) == 2));
        }
示例#27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CommonLogging"/> class.
        /// <para>
        /// Disallow creation of instances beyond the one instance for the process. The one instance
        /// is accessible via GetLoggingScenarioSingleton() (see below).
        /// </para>
        /// </summary>
        public CommonLogging()
        {
            LogFileGeneratedCount = 0;

            logChannel = new LoggingChannel(CommonConstants.LogDefaultChannelName, null);
            logChannel.LoggingEnabled += OnChannelLoggingEnabled;

            //Prism.PrismApplicationBase.Current.Resuming += OnAppResuming;

            //Prism.PrismApplicationBase.Current.Suspending += PrepareToSuspend;

            // If the app is being launched (not resumed), the following call will activate logging
            // if it had been activated during the last suspend.
            ResumeLoggingIfApplicable();
        }
示例#28
0
 protected virtual void Dispose(bool disposing)
 {
     if (isDisposed == false)
     {
         isDisposed = true;
         if (channel != null)
         {
             channel.Dispose();
             channel = null;
         }
         if (session != null)
         {
             session.Dispose();
             session = null;
         }
     }
 }
示例#29
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        private void Dispose(Boolean disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                if (_logChannel != null)
                {
                    _logChannel.Dispose();
                    _logChannel = null;
                }
            }

            disposed = true;
        }
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     using (var loggingChannel = new LoggingChannel("my provider", null, new Guid(loggingChannelId)))
     {
         loggingChannel.LogMessage("Back ground task started");
         if (taskInstance == null)
         {
             return;
         }
         taskDeferral = taskInstance.GetDeferral();
         LocalDataStore.CreateLocalConfigurationSettings();
         // taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
         var processor = new Processor(loggingChannel);
         processor.Process();
         Thread.Sleep(28800000);//ToDo-Temporary provision to run this service for a specified period(8 hours)..Should add Scheduler logic.
         taskDeferral.Complete();
         loggingChannel.LogMessage("Task completed at " + DateTime.UtcNow.ToString());
     }
 }
示例#31
0
        /// <summary>
        /// Construct a LoggingChannel with the Windows 10 constructor, then
        /// use the LoggingChannel for the scenario. Also show the use cases
        /// for the two Windows 10 constructors.
        /// See this sample's README for further discussion.
        /// </summary>
        public void LogWithWin10Constructor()
        {
            /*
             * If a LoggingChannel is used as a local or member variable, it should
             * be closed (disposed) when no longer needed. C# will do this automatically
             * if you enclose the usage in a using block.
             */

            // The 2-parameter constructor creates a channel with Windows 10 semantics.
            using (var channel = new LoggingChannel(
                       "SampleProvider",
                       null)) // null means use default options.
            {
                // The Id is generated by hashing the string "SampleProvider".
                // channel.Id == eff1e128-4903-5093-096a-bdc29b38456f

                this.DemonstrateLogging(channel);
            }

            /*
             * Demonstrate other (less-common) constructor scenarios:
             */

            // This creates a channel with Windows 10 semantics and declared
            // membership in a provider group.
            using (var channel = new LoggingChannel(
                       "SampleProvider",
                       new LoggingChannelOptions(new Guid("2e0582f3-d1b6-516a-9de3-9fd79ef952f8")))) // Join a provider group
            {
                // The Id is generated by hashing the string "SampleProvider".
                // channel.Id == eff1e128-4903-5093-096a-bdc29b38456f
            }

            // This creates a channel with Windows 10 semantics and a specific
            // provider Id.
            using (var channel = new LoggingChannel(
                       "SampleProvider",
                       null,
                       new Guid("2e0582f3-d1b6-516a-9de3-9fd79ef952f8")))
            {
                // channel.Id == 2e0582f3-d1b6-516a-9de3-9fd79ef952f8
            }
        }
示例#32
0
        /// <summary>
        /// Construct a LoggingChannel with the Windows 8.1 constructor, then
        /// use the LoggingChannel for the scenario.
        /// See this sample's README for further discussion.
        /// </summary>
        public void LogWithWin81Constructor()
        {
            /*
             * If a LoggingChannel is used as a local or member variable, it should
             * be closed (disposed) when no longer needed. C# will do this automatically
             * if you enclose the usage in a using block.
             */

            // The 1-parameter constructor creates a channel with Windows 8.1 semantics.
#pragma warning disable 618 // Disable warning for use of obsolete LoggingChannel constructor.
            using (var channel = new LoggingChannel("SampleProvider"))
            {
                // The Id for a Windows 8.1-mode channel is always the same.
                // channel.Id == 4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a

                this.DemonstrateLogging(channel);
            }
#pragma warning restore 618
        }
        /// <summary>
        /// Disallow creation of instances beyond the one instance for the process.
        /// The one instance is accessible via the Instance property (see below).
        /// </summary>
        private FileLoggingSessionScenario()
        {
            LogFileGeneratedCount = 0;

            // This sample demonstrates LoggingSession using the Windows 8.1 LoggingChannel APIs.
#pragma warning disable 618 // LoggingChannel is obsolete
            channel = new LoggingChannel(DEFAULT_CHANNEL_NAME);
#pragma warning restore

            channel.LoggingEnabled += OnChannelLoggingEnabled;

            App.Current.Suspending += OnAppSuspending;
            App.Current.Resuming   += OnAppResuming;

            // If the app is being launched (not resumed), the
            // following call will activate logging if it had been
            // activated during the last suspend.
            ResumeLoggingIfApplicable();
        }
 static AdalTrace()
 {
     AdalLoggingChannel = new LoggingChannel("Microsoft.IdentityModel.Clients.ActiveDirectory");            
 }
 public LoggingChannelEvents(LoggingChannel This)
 {
     this.This = This;
 }
        /// <summary>
        /// Construct a LoggingChannel with the Windows 10 constructor, then
        /// use the LoggingChannel for the scenario. Also show the use cases
        /// for the two Windows 10 constructors.
        /// </summary>
        public void LogWithWin10Constructor()
        {
            /*
            You can collect the events generated by this method with xperf or another
            ETL controller tool. To collect these events in an ETL file:

            xperf -start MySession -f MyFile.etl -on eff1e128-4903-5093-096a-bdc29b38456f
            (run the sample and click the "Windows 10 behavior" button)
            xperf -stop MySession

            After collecting the ETL file, you can decode the trace using xperf, wpa,
            or tracerpt. For example, to decode MyFile.etl with tracerpt:

            tracerpt MyFile.etl
            (generates dumpfile.xml)

            Note that decoding TraceLogging events requires Windows 10. Earlier versions
            of Windows can only reliably decode the simple (manifest-based) events.
            */

            /*
            If a LoggingChannel is created using the 2-parameter or 3-parameter
            constructors, it will use Windows 10 semantics:

            - The channel's ETW Provider Id can be controlled by the developer.
            - The channel's ETW Name is the same as the Channel Name.
            - The LoggingChannelName field is not automatically added to each event.
            - All events will be written using TraceLogging encoding.
            
            The 1-parameter constructor is marked as obsolete to ensure that
            developers are aware of the changes in semantics. The Windows 10 semantics
            are useful because they enable use of the ETW Provider Id for event
            filtering.

            The 2-parameter constructor accepts a channel name and channel options.
            If the options parameter is null, default options are used. At present,
            the only available option is the channel's group GUID. When using the
            2-parameter constructor, the channel's ETW Id is determined by hashing
            the channel name. (The hashing algorithm is the same as the one used by
            the .NET EventSource class.)

            The 3-parameter constructor accepts channel name, channel options, and
            the ETW Id. This constructor should be used when you need your channel
            to use a specific ETW Id and cannot use the default hashed channel name
            as your ETW Id.
            */

            /*
            If a LoggingChannel is used as a local or member variable, it should
            be closed (disposed) when no longer needed. C# will do this automatically
            if you enclose the usage in a using block.
            */

            // The 2-parameter constructor creates a channel with Windows 10 semantics.
            using (var channel = new LoggingChannel(
                "SampleProvider",
                null)) // null means use default options.
            {
                // The Id is generated by hashing the string "SampleProvider".
                // channel.Id == eff1e128-4903-5093-096a-bdc29b38456f

                this.DemonstrateLogging(channel);
            }

            /*
            Demonstrate other (less-common) constructor scenarios:
            */

            // This creates a channel with Windows 10 semantics and declared
            // membership in a provider group.
            using (var channel = new LoggingChannel(
                "SampleProvider",
                new LoggingChannelOptions(new Guid("2e0582f3-d1b6-516a-9de3-9fd79ef952f8")))) // Join a provider group
            {
                // The Id is generated by hashing the string "SampleProvider".
                // channel.Id == eff1e128-4903-5093-096a-bdc29b38456f
            }

            // This creates a channel with Windows 10 semantics and a specific
            // provider Id.
            using (var channel = new LoggingChannel(
                "SampleProvider",
                null,
                new Guid("2e0582f3-d1b6-516a-9de3-9fd79ef952f8")))
            {
                // channel.Id == 2e0582f3-d1b6-516a-9de3-9fd79ef952f8
            }
        }
        /// <summary>
        /// Disallow creation of instances beyond the one instance for the process.
        /// The one instance is accessible via the Instance property (see below).
        /// </summary>
        private LoggingSessionScenario()
        {
            LogFileGeneratedCount = 0;

            // This sample demonstrates LoggingSession using the Windows 8.1 LoggingChannel APIs.
#pragma warning disable 618 // LoggingChannel is obsolete
            channel = new LoggingChannel(DEFAULT_CHANNEL_NAME);
#pragma warning restore

            channel.LoggingEnabled += OnChannelLoggingEnabled;

            App.Current.Suspending += OnAppSuspending;
            App.Current.Resuming += OnAppResuming;

            // If the app is being launched (not resumed), the
            // following call will activate logging if it had been
            // activated during the last suspend.
            ResumeLoggingIfApplicable();
        }
        /// <summary>
        /// This method demonstrates the LoggingChannel and LoggingActivity APIs.
        /// </summary>
        /// <param name="channel">
        /// The channel to use for the demonstration. This channel may have been
        /// constructed using a Windows 8.1 constructor or a Windows 10 constructor.
        /// The same APIs are supported in both cases, but the ETL events will be
        /// formatted a bit differently depending on how the channel was constructed.
        /// </param>
        private void DemonstrateLogging(LoggingChannel channel)
        {
            // Whenever any ETW session changes the way it is listening to this
            // channel, the LoggingEnable event is fired. For example, this might
            // be called when a session begins listening, changes the level at
            // which it is listening, or stops listening.
            channel.LoggingEnabled += this.OnLoggingEnabled;

            // Log simple string events
            channel.LogMessage("Simple message"); // default level is Verbose
            channel.LogMessage("Simple error", LoggingLevel.Error);

            // Log simple string + integer events.
            channel.LogValuePair("Simple message", 123); // default level is Verbose
            channel.LogValuePair("Simple error", 456, LoggingLevel.Error);

            // The channel.Name property returns the name that was used when the
            // channel was constructed. When running in Windows 10 mode, the name
            // is already set as the provider name, so no LoggingChannelName is
            // automatically added to the event.
            channel.LogMessage(channel.Name);

            // The channel.Id property is new to Windows 10.
            channel.LogMessage(channel.Id.ToString());

            // If you want to avoid the overhead of collecting data when nobody is
            // listening to your channel, check the Enabled property before logging.
            if (channel.Enabled)
            {
                channel.LogMessage(this.CollectExpensiveData());
            }

            // The IsEnabled() method is exactly the same as the Enabled property,
            // except that it is a new Windows 10 API.
            if (channel.IsEnabled())
            {
                channel.LogMessage(this.CollectExpensiveData());
            }

            // If you want to only collect data if somebody is listening at a specific
            // level, you need to check both Enabled and Level. Note that the value of
            // the Level is unspecified when Enabled is false.
            if (channel.Enabled && channel.Level <= LoggingLevel.Warning)
            {
                channel.LogMessage(this.CollectExpensiveData(), LoggingLevel.Warning);
            }

            // The IsEnabled(LoggingLevel) method is a bit nicer than checking both
            // Enabled and Level, but it is only available on Windows 10 or later.
            if (channel.IsEnabled(LoggingLevel.Warning))
            {
                channel.LogMessage(this.CollectExpensiveData(), LoggingLevel.Warning);
            }

            // You can also use IsEnabled to check for keywords.
            if (channel.IsEnabled(LoggingLevel.Information, 0x10))
            {
                channel.LogMessage(this.CollectExpensiveData(), LoggingLevel.Information);
            }

            // Use LoggingFields with the LogEvent method to write complex events.
            var fields = new LoggingFields();
            fields.AddDouble("pi", 3.14159);
            channel.LogEvent(
                "ComplexEvent",
                fields,
                LoggingLevel.Verbose,
                new LoggingOptions(0x10)); // Keywords = 0x10

            // You can add any number of name-value pairs to a fields object, though
            // you may encounter ETW limitations if you add too many. For example,
            // ETW is limited to a maximum event size of 64KB, and the current
            // TraceLogging decoder can handle no more than 128 fields.

            // Performance optimization: You can reuse a LoggingFields object to
            // avoid unnecessary allocations. Don't forget to call Clear()
            // between uses, and don't try to share a LoggingFields object between
            // threads.
            fields.Clear();
            fields.AddDateTime("Date", DateTimeOffset.Now);
            channel.LogEvent("Now", fields);

            fields.Clear();

            // You can add a formatting hint to affect the way a value is decoded.
            // Not all combinations are useful, and the hint may be ignored.
            // For example, you can encode an MBCS string by writing a byte array
            // with a String hint.
            fields.AddUInt8Array(
                "AnsiString",
                new byte[] { 65, 66, 67, 49, 50, 51 }, // "ABC123"
                LoggingFieldFormat.String);

            // You can add "tag" bits to a field. These are user-defined bits that
            // can be used to communicate with an event processing tool. For example,
            // you might define a tag bit to indicate that a field contains private
            // data that should not be displayed on-screen.
            fields.AddString("Password", "12345", LoggingFieldFormat.Default, 0x10);

            // You can add a "structure" to an event. A structure is a name for a
            // group of fields. Structures can nest. Call BeginStruct to add a level
            // of nesting, and call EndStruct after the last field of the structure.
            fields.BeginStruct("Nested");
                fields.AddInt16("Nested-1", 1);
                fields.AddInt16("Nested-2", 2);
                fields.BeginStruct("Nested-Nested");
                    fields.AddInt16("Nested-Nested-3", 3);
                fields.EndStruct();
                fields.AddInt16("Nested-4", 4);
            fields.EndStruct();

            // Advanced scenarios: you can use a LoggingOptions object to control
            // detailed event settings such as keywords, opcodes, and activity Ids.
            // These have their normal ETW semantics. You can also set event tags,
            // which are bit values that can be used to communicate with the event
            // processor.
            channel.LogEvent(
                "VeryComplexEvent",
                fields,
                LoggingLevel.Information,
                new LoggingOptions { Keywords = 0x123, Tags = 0x10 });

            // Windows 10 introduces the ILoggingTarget interface. LoggingChannel
            // implements this interface. This interface allows components to accept
            // a logger as an parameter.
            this.DoSomething(channel);

            /*
            If a LoggingActivity is created using a LoggingActivity constructor,
            it will use Windows 8.1 semantics:

            - If an activity is destroyed (garbage-collected) without being closed
              and the associated LoggingChannel is still open, the activity will
              write a default Stop event.
            - The default Stop event (written by the destructor or by the Close()
              method) is encoded as a "simple" event.

            The 8.1 semantics are deprecated because the automatic generation of
            a Stop event at garbage-collection can be misleading. The Stop event
            is intended to mark the a precise point at which an activity is
            completed, while the garbage-collection of an abandoned activity is
            inherently imprecise and unpredictable.

            If a LoggingActivity is created using a StartActivity method, it will
            use Windows 10 semantics:

            - If an activity is destroyed (garbage-collected) without being closed,
              there will be no Stop event for the activity.
            - The default Stop event (written by the Close() method) is encoded as
              a TraceLogging event with name "ActivityClosed".
            */

            // This activity is created with Windows 8.1 semantics.
            using (var a1 = new LoggingActivity("Activity1", channel))
            {
                // The activity Start event is written by the LoggingActivity constructor.
                // You would do your activity's work here.
                // The activity Stop event is written when the activity is closed (disposed).

                // The Windows 10 LoggingActivity adds new methods for writing events
                // that are marked as associated with the activity.
                a1.LogEvent("Activity event");

                // LoggingActivity also implements the ILoggingTarget interface, so you can
                // use either a channel or an activity as a logging target.
                this.DoSomething(a1);

                // The Windows 10 LoggingActivity adds new methods for creating nested activities.
                // Note that nested activities are always created with Windows 10 semantics,
                // even when nested under an activity that is using Windows 8.1 semantics.
                using (var a2 = a1.StartActivity("Activity2"))
                {
                    // Nested task occurs here.

                    // The Windows 10 LoggingActivity allows you to customize the Stop event.
                    a2.StopActivity("Activity 2 stop");
                }

                // Because a1 is using Windows 8.1 semantics, if we did not call Dispose(),
                // it would attempt to write a Stop event when it is garbage collected.
                // Writing Stop events during garbage collection is not useful, so be sure
                // to properly stop, close, or dispose activities.
            }

            // The Windows 10 StartActivity method creates a new activity, optionally with
            // specified fields and characteristics.
            // This activity is created with Windows 10 semantics.
            using (var a3 = channel.StartActivity("Activity3"))
            {
                // Because a3 is using Windows 10 semantics, if we did not call Dispose(),
                // there would be no Stop event (not even when the activity is garbage
                // collected). To get a Stop event, be sure to stop, close, or dispose the
                // activity.
            }
        }
        protected virtual void Dispose(bool disposing)
        {
            if (isDisposed == false)
            {
                isDisposed = true;

                if (disposing)
                {
                    if (channel != null)
                    {
                        channel.Dispose();
                        channel = null;
                    }

                    if (session != null)
                    {
                        session.Dispose();
                        session = null;
                    }
                }
            }
        }