Ejemplo n.º 1
0
        private void MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            LoggingFields messageHandlerLoggingFields = new LoggingFields();

#if DEBUG
            Debug.WriteLine($"{DateTime.UtcNow:HH:mm:ss}-MqttClient_ApplicationMessageReceived ClientId:{e.ClientId} Topic:{e.ApplicationMessage.Topic} Payload:{e.ApplicationMessage.ConvertPayloadToString()}");
#endif
            messageHandlerLoggingFields.AddString("ClientId", e.ClientId);
            messageHandlerLoggingFields.AddString("Topic", e.ApplicationMessage.Topic);
            messageHandlerLoggingFields.AddString("Payload", e.ApplicationMessage.ConvertPayloadToString());

            if (messageHandler != null)
            {
                try
                {
                    messageHandler.MqttApplicationMessageReceived(e);
                }
                catch (Exception ex)
                {
                    messageHandlerLoggingFields.AddString("Exception", ex.ToString());
                    this.logging.LogEvent("MqttClient_ApplicationMessageReceived MessageHandler failed", messageHandlerLoggingFields, LoggingLevel.Error);
                    return;
                }
            }
            this.logging.LogEvent("MqttClient_ApplicationMessageReceived", messageHandlerLoggingFields, LoggingLevel.Information);
        }
Ejemplo n.º 2
0
        private void WriteLog(string text,
                              LoggingLevel loggingLevel               = LoggingLevel.Verbose,
                              [CallerMemberName] string memberName    = "",
                              [CallerFilePath] string sourceFilePath  = "",
                              [CallerLineNumber] int sourceLineNumber = 0)
        {
            Debug.WriteLine($"[Log::{Enum.GetName(typeof(LoggingLevel), loggingLevel)}][{memberName}] {text}");

            if (_session == null || _channel == null)
            {
                Debug.WriteLine("Error: Logger is not initialized");
                return;
            }

            try
            {
                string message =
                    "Message: " + text + Environment.NewLine + Environment.NewLine +
                    "Member name: " + memberName + Environment.NewLine +
                    "Source file path: " + sourceFilePath + Environment.NewLine +
                    "Source line number: " + sourceLineNumber + Environment.NewLine;

                var fields = new LoggingFields();
                fields.AddString("MemberName", memberName);
                fields.AddString("SourceFilePath", sourceFilePath);
                fields.AddInt32("SourceLineNumber", sourceLineNumber);
                fields.AddString("Message", text);

                _channel.LogEvent("LogEvent", fields, loggingLevel);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("[Log] " + ex);
            }
        }
Ejemplo n.º 3
0
 public void LogEvent(LoggingLevel l, string name, LoggingFields f = null)
 {
     Task.Run(() =>
     {
         channel.LogEvent(name, f, l);
     });
 }
Ejemplo n.º 4
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            LoggingFields startupInformation = new LoggingFields();

            this.logging.LogEvent("Application starting");

            try
            {
                this.mediaCapture = new MediaCapture();
                this.mediaCapture.InitializeAsync().AsTask().Wait();
                Debug.WriteLine("Camera configuration success");

                GpioController gpioController = GpioController.GetDefault();

                this.interruptGpioPin = gpioController.OpenPin(InterruptPinNumber);
                this.interruptGpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
                this.interruptGpioPin.ValueChanged += this.InterruptGpioPin_ValueChanged;
                Debug.WriteLine("Digital Input Interrupt configuration success");
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Camera or digital input configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            startupInformation.AddString("PrimaryUse", this.mediaCapture.VideoDeviceController.PrimaryUse.ToString());
            startupInformation.AddInt32("Interrupt pin", InterruptPinNumber);

            this.logging.LogEvent("Application started", startupInformation);

            // enable task to continue running in background
            this.backgroundTaskDeferral = taskInstance.GetDeferral();
        }
        private async void InterruptGpioPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
        {
            DateTime currentTime = DateTime.UtcNow;

            Debug.WriteLine($"{DateTime.UtcNow.ToLongTimeString()} Digital Input Interrupt {sender.PinNumber} triggered {args.Edge}");

            if (args.Edge == this.interruptTriggerOn)
            {
                return;
            }

            // Check that enough time has passed for picture to be taken
            if ((currentTime - this.imageLastCapturedAtUtc) < this.debounceTimeout)
            {
                return;
            }

            this.imageLastCapturedAtUtc = currentTime;

            // Just incase - stop code being called while photo already in progress
            if (this.cameraBusy)
            {
                return;
            }

            this.cameraBusy = true;

            try
            {
                string localFilenameLatest  = string.Format(this.localStorageimageFilenameLatestFormat, Environment.MachineName.ToLower(), currentTime);
                string localFilenameHistory = string.Format(this.localStorageImageFilenameHistoryFormat, Environment.MachineName.ToLower(), currentTime);

                StorageFile photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync(localFilenameLatest, CreationCollisionOption.ReplaceExisting);

                ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
                await this.mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photoFile);

                LoggingFields imageInformation = new LoggingFields();
                imageInformation.AddDateTime("TakenAtUTC", currentTime);
                imageInformation.AddString("LocalFilename", photoFile.Path);
                imageInformation.AddString("LocalFilenameHistory", localFilenameHistory);
                this.logging.LogEvent("Saving image(s) to local storage", imageInformation);

                // copy the historic image to storage
                if (!string.IsNullOrWhiteSpace(localFilenameHistory))
                {
                    await photoFile.CopyAsync(KnownFolders.PicturesLibrary, localFilenameHistory);

                    this.logging.LogEvent("Image history saved to local storage");
                }
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Camera photo save or upload failed " + ex.Message, LoggingLevel.Error);
            }
            finally
            {
                this.cameraBusy = false;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Track an exception.
        /// </summary>
        /// <param name="ex">Instance of <see cref="Exception"/></param>
        public static async void TrackExceptionAsync(Exception ex)
        {
            if (!OptinTelemetry || ex == null)
            {
                return;
            }
            if (!_isInitialized)
            {
                await InitializeInternalAsync();
            }
            TelemetryClient.TrackException(ex);

            try
            {
                var lgFields = new LoggingFields();
                lgFields.AddString("Message", ex.Message ?? string.Empty, LoggingFieldFormat.String);
                lgFields.AddString("StackTrace", ex.StackTrace ?? string.Empty, LoggingFieldFormat.String);
                lgFields.AddString("Detailed", ex.ToString(), LoggingFieldFormat.String);

                LogEventWithParams(ExceptionEvent, lgFields, LoggingLevel.Error);
            }
            catch
            {
                // Ignore
            }
        }
Ejemplo n.º 7
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            LoggingFields startupInformation = new LoggingFields();

            this.logging.LogEvent("Application starting");

            try
            {
                this.mediaCapture = new MediaCapture();
                this.mediaCapture.InitializeAsync().AsTask().Wait();

                this.imageUpdatetimer = new Timer(this.ImageUpdateTimerCallback, null, this.imageUpdateDueDefault, this.imageUpdatePeriodDefault);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Camera configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            startupInformation.AddString("PrimaryUse", this.mediaCapture.VideoDeviceController.PrimaryUse.ToString());
            startupInformation.AddTimeSpan("Due", this.imageUpdateDueDefault);
            startupInformation.AddTimeSpan("Period", this.imageUpdatePeriodDefault);

            this.logging.LogEvent("Application started", startupInformation);

            // enable task to continue running in background
            this.backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Ejemplo n.º 8
0
        private void Rfm9XDevice_OnReceive(object sender, Rfm9XDevice.OnDataReceivedEventArgs e)
        {
            LoggingFields messageHandlerLoggingFields = new LoggingFields();

#if DEBUG
            Debug.WriteLine($"{DateTime.UtcNow:HH:mm:ss}-OnReceive From:{BitConverter.ToString(e.Address)} PacketSnr:{e.PacketSnr:0.0} Packet RSSI:{e.PacketRssi}dBm RSSI:{e.Rssi}dBm Length:{e.Data.Length}");
#endif
            messageHandlerLoggingFields.AddString("PacketSNR", e.PacketSnr.ToString("F1"));
            messageHandlerLoggingFields.AddInt32("PacketRSSI", e.PacketRssi);
            messageHandlerLoggingFields.AddInt32("RSSI", e.Rssi);

            string addressBcdText = BitConverter.ToString(e.Address);
            messageHandlerLoggingFields.AddInt32("DeviceAddressLength", e.Address.Length);
            messageHandlerLoggingFields.AddString("DeviceAddressBCD", addressBcdText);

            if (messageHandler != null)
            {
                try
                {
                    messageHandler.Rfm9XOnReceive(e);
                }
                catch (Exception ex)
                {
                    messageHandlerLoggingFields.AddString("MessageHandler Exception", ex.ToString());
                    this.logging.LogEvent("Rfm9XDevice_OnReceive", messageHandlerLoggingFields, LoggingLevel.Error);
                    return;
                }
            }
            this.logging.LogEvent("Rfm9XDevice_OnReceive", messageHandlerLoggingFields, LoggingLevel.Information);
        }
Ejemplo n.º 9
0
        public void Verbose(string message)
        {
            var fields = new LoggingFields();

            fields.AddString("Message", message);
            this.channel.LogEvent(TraceEventName, fields, LoggingLevel.Verbose);
        }
Ejemplo n.º 10
0
        public static LoggingChannel log = new LoggingChannel("GPSCam", null); // Guid généré automatiquement est : {
        private void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LoggingFields champs = new LoggingFields();

            champs.AddString("MESSAGE", e.Exception.ToString());
            log.LogEvent("EXCEPTION", champs, LoggingLevel.Error);
            e.Handled = true;
        }
Ejemplo n.º 11
0
        public void LogDataLightSensor(LightSensorReading reading)
        {
            LoggingFields loggingFields = new LoggingFields();

            loggingFields.AddString("Timestamp", reading.Timestamp.ToString());
            loggingFields.AddDouble("IlluminanceInLux", reading.IlluminanceInLux);
            rootPage.loggingChannelView.LogEvent("LightSensorData", loggingFields);
        }
Ejemplo n.º 12
0
        public static void Trace(string message)
        {
            LoggingFields fields = new LoggingFields();

            fields.AddString("Message", message);
            Logger.LogEvent("DebugTrace", fields, EventVerbosity.Verbose);
            Debug.WriteLine(message);
        }
Ejemplo n.º 13
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;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Given an existing <see cref="LoggingFields"/> reference, adds additional fields for an exception.
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public static LoggingFields AugmentLoggingFields(this Exception exception, LoggingFields fields)
        {
            fields.AddString("ExceptionType", exception?.GetType()?.ToString() ?? "[None]");
            fields.AddString("ExceptionMessage", exception?.Message ?? "[None]");
            fields.AddString("ExceptionStack", exception?.StackTrace ?? "[None]");
            fields.AddString("InnerException", exception?.InnerException?.ToString() ?? "[None]");

            return(fields);
        }
Ejemplo n.º 15
0
        private async void ImageUpdateTimerCallback(object state)
        {
            DateTime currentTime = DateTime.UtcNow;

            Debug.WriteLine($"{DateTime.UtcNow.ToLongTimeString()} Timer triggered");

            // Just incase - stop code being called while photo already in progress
            if (cameraBusy)
            {
                return;
            }
            cameraBusy = true;

            try
            {
                string localFilename     = string.Format(localImageFilenameLatestFormat, currentTime);
                string folderNameHistory = string.Format(localFolderNameHistoryFormat, currentTime);
                string filenameHistory   = string.Format(localImageFilenameHistoryFormat, currentTime);

                StorageFile photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync(localFilename, CreationCollisionOption.ReplaceExisting);

                ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
                await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photoFile);

                LoggingFields imageInformation = new LoggingFields();
                imageInformation.AddDateTime("TakenAtUTC", currentTime);
                imageInformation.AddString("LocalFilename", photoFile.Path);
                imageInformation.AddString("FolderNameHistory", folderNameHistory);
                imageInformation.AddString("FilenameHistory", filenameHistory);
                this.logging.LogEvent("Image saved to local storage", imageInformation);

                // Upload the historic image to storage
                if (!string.IsNullOrWhiteSpace(folderNameHistory) && !string.IsNullOrWhiteSpace(filenameHistory))
                {
                    // Check to see if historic images folder exists and if it doesn't create it
                    IStorageFolder storageFolder = (IStorageFolder)await KnownFolders.PicturesLibrary.TryGetItemAsync(folderNameHistory);

                    if (storageFolder == null)
                    {
                        storageFolder = await KnownFolders.PicturesLibrary.CreateFolderAsync(folderNameHistory);
                    }
                    await photoFile.CopyAsync(storageFolder, filenameHistory, NameCollisionOption.ReplaceExisting);

                    this.logging.LogEvent("Image historic saved to local storage", imageInformation);
                }
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Image capture or save failed " + ex.Message, LoggingLevel.Error);
            }
            finally
            {
                cameraBusy = false;
            }
        }
Ejemplo n.º 16
0
        private async Task <MethodResponse> DeviceSendAsync(MethodRequest methodRequest, object userContext)
        {
            LoggingFields sendLoggingInfo = new LoggingFields();

            this.logging.LogEvent("Send BCD initiated");

            try
            {
                // Initially use a dynamic maybe use a decorated class in future
                dynamic json = JValue.Parse(methodRequest.DataAsJson);

                string deviceAddressBcd = json.DeviceAddress;
                sendLoggingInfo.AddString("DeviceAddressBCD", deviceAddressBcd);
                Debug.WriteLine($"DeviceSendAsync DeviceAddressBCD {deviceAddressBcd}");

                byte[] deviceAddressBytes = deviceAddressBcd.Split('-').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray();
                sendLoggingInfo.AddInt32("DeviceAddressBytes Length", deviceAddressBytes.Length);
                Debug.WriteLine($"DeviceSendAsync DeviceAddressLength {deviceAddressBytes.Length}");

                if ((deviceAddressBytes.Length < Rfm9XDevice.AddressLengthMinimum) || (deviceAddressBytes.Length > Rfm9XDevice.AddressLengthMaximum))
                {
                    this.logging.LogEvent("DeviceSendAsync failed device address bytes length", sendLoggingInfo, LoggingLevel.Error);
                    return(new MethodResponse(414));
                }

                string messagedBcd = json.DevicePayload;
                sendLoggingInfo.AddString("MessageBCD", messagedBcd);

                byte[] messageBytes = messagedBcd.Split('-').Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray();                 // changed the '-' to ' '
                sendLoggingInfo.AddInt32("MessageBytesLength", messageBytes.Length);
                Debug.WriteLine($"DeviceSendAsync DeviceAddress:{deviceAddressBcd} Payload:{messagedBcd}");

                if ((messageBytes.Length < Rfm9XDevice.MessageLengthMinimum) || (messageBytes.Length > Rfm9XDevice.MessageLengthMaximum))
                {
                    this.logging.LogEvent("DeviceSendAsync failed payload Length", sendLoggingInfo, LoggingLevel.Error);
                    return(new MethodResponse(413));
                }

                if (sendMessageQueue.TryAdd(deviceAddressBytes, messageBytes))
                {
                    this.logging.LogEvent("DeviceSendAsync failed message already queued", sendLoggingInfo, LoggingLevel.Error);
                    return(new MethodResponse(409));
                }

                this.logging.LogEvent("DeviceSendAsync success", sendLoggingInfo, LoggingLevel.Information);
            }
            catch (Exception ex)
            {
                sendLoggingInfo.AddString("Exception", ex.ToString());
                this.logging.LogEvent("DeviceSendAsync failed exception", sendLoggingInfo, LoggingLevel.Error);
                return(new MethodResponse(400));
            }

            return(new MethodResponse(200));
        }
Ejemplo n.º 17
0
        private void PopulateAppInfo(LoggingFields fields)
        {
            var appId           = CoreApplication.Id;
            var aumId           = Package.Current.Id.FamilyName + "!" + appId;
            var packageFullName = Package.Current.Id.FullName;
            var psmKey          = Package.Current.Id.FullName + "+" + appId;

            fields.AddString("AumId", aumId);
            fields.AddString("PackageFullName", packageFullName);
            fields.AddString("PsmKey", psmKey);
        }
Ejemplo n.º 18
0
        private void SensorValueupload(object state)
        {
            try
            {
                // Air sensor readings
                double temperatureCelsius    = bme280Sensor.Temperature.DegreesCelsius;
                double temperatureFahrenheit = bme280Sensor.Temperature.DegreesFahrenheit;
                double humidity = bme280Sensor.Humidity;
                double pressure = bme280Sensor.Pressure.Kilopascals;

                double lightLevel    = GroveBaseHatAnalogPorts.Read(AnalogPorts.AnalogPort.A0);
                double soilMoisture1 = GroveBaseHatAnalogPorts.Read(AnalogPorts.AnalogPort.A2);
                double soilMoisture2 = GroveBaseHatAnalogPorts.Read(AnalogPorts.AnalogPort.A4);

                LoggingService.Log(string.Format("C {0:0.0}° F {1:0.0}° H {2:0}% P {3:0.000}kPa L {4:0}%  Soil1 {5:0}% Soil2 {6:0}% ", temperatureCelsius, temperatureFahrenheit, humidity, pressure, lightLevel, soilMoisture1, soilMoisture2));

                // Setup for the the logging of sensor values
                var loggingData = new LoggingFields();

                // Construct Azure IoT Central friendly payload
                var telemetryDataPoint = new TelemetryDataPoint();
                telemetryDataPoint.Celsius = temperatureCelsius;
                loggingData.AddDouble(nameof(telemetryDataPoint.Celsius), temperatureCelsius);
                telemetryDataPoint.Fahrenheit = temperatureFahrenheit;
                loggingData.AddDouble(nameof(telemetryDataPoint.Fahrenheit), temperatureFahrenheit);
                telemetryDataPoint.Humidity = humidity;
                loggingData.AddDouble(nameof(telemetryDataPoint.Humidity), humidity);
                telemetryDataPoint.Pressure = pressure;
                loggingData.AddDouble(nameof(telemetryDataPoint.Pressure), pressure);

                telemetryDataPoint.Light = lightLevel;
                loggingData.AddDouble(nameof(telemetryDataPoint.Light), lightLevel);

                telemetryDataPoint.SoilMoisture1 = soilMoisture1;
                loggingData.AddDouble(nameof(telemetryDataPoint.SoilMoisture1), soilMoisture1);
                telemetryDataPoint.SoilMoisture2 = soilMoisture2;
                loggingData.AddDouble(nameof(telemetryDataPoint.SoilMoisture2), soilMoisture2);

                // Log the sensor values to ETW logging
                LoggingService.LogEvent("Sensor readings", loggingData, LoggingLevel.Verbose);

                using (var message = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(telemetryDataPoint))))
                {
                    LoggingService.Log("AzureIoTHubClient SendEventAsync starting");
                    azureIoTHubClient.SendEventAsync(message).Wait();
                    LoggingService.Log("AzureIoTHubClient SendEventAsync finished");
                }
            }
            catch (Exception ex)
            {
                LoggingService.Error("Failed to send telemetry", ex);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Handles application memory limit changes.
        /// </summary>
        /// <param name="e">Instance of <see cref="AppMemoryUsageLimitChangingEventArgs"/>.</param>
        private void OnAppMemroyUsageLimitChanging(object sender, AppMemoryUsageLimitChangingEventArgs e)
        {
            if (MemoryManager.AppMemoryUsage >= e.NewLimit)
            {
                var fields = new LoggingFields();
                fields.AddUInt64("CurrentUsage", MemoryManager.AppMemoryUsage);
                fields.AddUInt64("NewLimit", e.NewLimit);
                TelemetryHelper.LogEventWithParams("MemUsageChanging", fields);

                ReduceMemoryUsage();
            }
        }
Ejemplo n.º 20
0
        public static void Assert(bool condition, string message)
        {
            if (!condition)
            {
                LoggingFields fields = new LoggingFields();
                fields.AddString("Message", message);
                Logger.LogEvent("AssertionFailed", fields, EventVerbosity.Critical);

                Debug.WriteLine("AssertionFailed: " + message);
                Debugger.Break();
            }
        }
Ejemplo n.º 21
0
        public void ResumeVisibleComplete()
        {
            if (!GetTraceLoggingProviderEnabled())
            {
                return;
            }

            LoggingFields fields = new LoggingFields();

            PopulateAppInfo(fields);
            LogAppLifecycleEvent("ModernAppResume_VisibleComplete", fields);
        }
Ejemplo n.º 22
0
        public void LaunchUIResponsive()
        {
            if (!GetTraceLoggingProviderEnabled())
            {
                return;
            }

            LoggingFields fields = new LoggingFields();

            PopulateAppInfo(fields);
            LogAppLifecycleEvent("ModernAppLaunch_UIResponsive", fields);
        }
Ejemplo n.º 23
0
        async Task PayloadText(DeviceClient azureIoTHubClient, Rfm9XDevice.OnDataReceivedEventArgs e)
        {
            JObject       telemetryDataPoint   = new JObject();
            LoggingFields processLoggingFields = new LoggingFields();

            processLoggingFields.AddString("PacketSNR", e.PacketSnr.ToString("F1"));
            telemetryDataPoint.Add("PacketSNR", e.PacketSnr.ToString("F1"));
            processLoggingFields.AddInt32("PacketRSSI", e.PacketRssi);
            telemetryDataPoint.Add("PacketRSSI", e.PacketRssi);
            processLoggingFields.AddInt32("RSSI", e.Rssi);
            telemetryDataPoint.Add("RSSI", e.Rssi);

            string addressBcdText = BitConverter.ToString(e.Address);

            processLoggingFields.AddInt32("DeviceAddressLength", e.Address.Length);
            processLoggingFields.AddString("DeviceAddressBCD", addressBcdText);
            telemetryDataPoint.Add("DeviceAddressBCD", addressBcdText);

            string messageBcdText = BitConverter.ToString(e.Data);

            processLoggingFields.AddInt32("MessageLength", e.Data.Length);
            processLoggingFields.AddString("MessageBCD", messageBcdText);

            try
            {
                string messageText = UTF8Encoding.UTF8.GetString(e.Data);
                processLoggingFields.AddString("MessageText", messageText);
                telemetryDataPoint.Add("Payload", messageText);
            }
            catch (Exception)
            {
                this.logging.LogEvent("PayloadProcess failure converting payload to text", processLoggingFields, LoggingLevel.Warning);
                return;
            }

            try
            {
                using (Message message = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(telemetryDataPoint))))
                {
                    Debug.WriteLine(" {0:HH:mm:ss} AzureIoTHubClient SendEventAsync start", DateTime.UtcNow);
                    await this.azureIoTHubClient.SendEventAsync(message);

                    Debug.WriteLine(" {0:HH:mm:ss} AzureIoTHubClient SendEventAsync finish", DateTime.UtcNow);
                }
                this.logging.LogEvent("SendEventAsync Text payload", processLoggingFields, LoggingLevel.Information);
            }
            catch (Exception ex)
            {
                processLoggingFields.AddString("Exception", ex.ToString());
                this.logging.LogEvent("SendEventAsync Text payload", processLoggingFields, LoggingLevel.Error);
            }
        }
Ejemplo n.º 24
0
        public bool ToFile(LoggingFields logFields, LoggingType loggingType)
        {
            bool retVal = false;

            string DtTm     = DateTime.Now.ToString(LoggingConstants.LogDateTimeFormat);
            string fileName = string.Format(LoggingConstants.TextFileName, logFields.AppName, DateTime.Now.ToString(LoggingConstants.LogFileDateTimeFormat));
            string filePath = @LogFileUri + fileName;

            try
            {
                using (StreamWriter file = File.AppendText(filePath))
                {
                    switch (loggingType)
                    {
                    case LoggingType.Information:
                    case LoggingType.Warning:
                        file.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}", DtTm, LoggingConstants.SourceLogName, loggingType, logFields.AppName, logFields.LogMessage));
                        retVal = true;
                        break;

                    case LoggingType.Exception:
                        file.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", DtTm, LoggingConstants.SourceLogName, loggingType, logFields.AppName, logFields.ExceptionMessage, logFields.ExceptionStackTrace));
                        retVal = true;
                        break;

                    case LoggingType.ExceptionWithMessage:
                        file.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", DtTm, LoggingConstants.SourceLogName, loggingType, logFields.AppName, logFields.ExceptionMessage, logFields.ExceptionStackTrace, logFields.LogMessage));
                        retVal = true;
                        break;

                    case LoggingType.Performance:
                        file.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", DtTm, LoggingConstants.SourceLogName, loggingType, logFields.AppName, logFields.PerformanceStartTime, logFields.PerformanceEndTime, logFields.LogMessage));
                        retVal = true;
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (DirectoryNotFoundException)
            {
                retVal = false;
                //throw new ArgumentException(LoggingConstants.Log_DirectoryNotFoundException);
            }
            catch
            {
                retVal = false;
            }

            return(retVal);
        }
Ejemplo n.º 25
0
        public void Log(Exception e)
        {
            Task.Run(() =>
            {
                var a = new LoggingFields();
                a.AddString("Type", e.GetType().Name);
                a.AddString("Message", e.Message);

                PushException(ref a, e);

                channel.LogEvent("Exception_Occured", a, LoggingLevel.Error);
            });
        }
Ejemplo n.º 26
0
        public bool LogException(string appName, Exception ex)
        {
            Guard.Against.LogAppNameEmpty(appName);

            logFields = new LoggingFields
            {
                AppName             = appName,
                ExceptionMessage    = ex.Message,
                ExceptionStackTrace = ex.StackTrace
            };

            return(loggingHelper.ToFile(logFields, LoggingType.Exception));
        }
Ejemplo n.º 27
0
        public bool LogInformation(string appName, string logMessage)
        {
            Guard.Against.LogAppNameEmpty(appName);
            Guard.Against.LogMessageEmpty(logMessage);

            logFields = new LoggingFields
            {
                AppName    = appName,
                LogMessage = logMessage
            };

            return(loggingHelper.ToFile(logFields, LoggingType.Information));
        }
Ejemplo n.º 28
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    loggingHelper = null;
                    logFields     = null;
                }

                disposedValue = true;
            }
        }
Ejemplo n.º 29
0
        public void ResizeVisibleComplete(int viewId)
        {
            if (!GetTraceLoggingProviderEnabled())
            {
                return;
            }

            LoggingFields fields = new LoggingFields();

            PopulateAppInfo(fields);
            fields.AddInt32("ViewId", viewId);
            LogAppLifecycleEvent("ModernAppResize_VisibleComplete", fields);
        }
Ejemplo n.º 30
0
        void IMessageHandler.MqttApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            LoggingFields processReceiveLoggingFields = new LoggingFields();

            processReceiveLoggingFields.AddString("ClientId", e.ClientId);
#if DEBUG
            processReceiveLoggingFields.AddString("Payload", e.ApplicationMessage.ConvertPayloadToString());
#endif
            processReceiveLoggingFields.AddString("QualityOfServiceLevel", e.ApplicationMessage.QualityOfServiceLevel.ToString());
            processReceiveLoggingFields.AddBoolean("Retain", e.ApplicationMessage.Retain);
            processReceiveLoggingFields.AddString("Topic", e.ApplicationMessage.Topic);

            this.Logging.LogEvent("MqttApplicationMessageReceived topic not processed", processReceiveLoggingFields, LoggingLevel.Error);
        }
        /// <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.
            }
        }