repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using log4net.Repository.Hierarchy; using log4net.Core; using log4net.Appender; using log4net.Layout; using AWS.Logger.Log4net; namespace ProgrammaticConfigurationExample { class Program { static void Main(string[] args) { ConfigureLog4net(); ILog log = LogManager.GetLogger(typeof(Program)); log.Info("Check the AWS Console CloudWatch Logs console in us-east-1"); log.Info("to see messages in the log streams for the"); log.Info("log group Log4net.ProgrammaticConfigurationExample"); } static void ConfigureLog4net() { Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(); PatternLayout patternLayout = new PatternLayout(); patternLayout.ConversionPattern = "%-4timestamp [%thread] %-5level %logger %ndc - %message%newline"; patternLayout.ActivateOptions(); AWSAppender appender = new AWSAppender(); appender.Layout = patternLayout; // Set log group and region. Assume credentials will be found using the default profile or IAM credentials. appender.LogGroup = "Log4net.ProgrammaticConfigurationExample"; appender.Region = "us-east-1"; appender.ActivateOptions(); hierarchy.Root.AddAppender(appender); hierarchy.Root.Level = Level.All; hierarchy.Configured = true; } } }
52
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ProgrammaticConfigurationExample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ProgrammaticConfigurationExample")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3a725e5c-a78b-4724-9934-ad2d96a158c6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using NLog; namespace NLog.ConfigExample { class Program { static void Main(string[] args) { // NLog is configured in the NLog.config Logger logger = LogManager.GetCurrentClassLogger(); logger.Info("Check the AWS Console CloudWatch Logs console in us-east-1"); logger.Info("to see messages in the log streams for the"); logger.Info("log group NLog.ConfigExample"); } } }
25
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NLogSample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NLogSample")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("71373ec1-b7cd-41e5-9aee-2d58269079a2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NLog; using NLog.Targets; using NLog.Config; using NLog.AWS.Logger; namespace ProgrammaticConfigurationExample { class Program { static void Main(string[] args) { ConfigureNLog(); Logger logger = LogManager.GetCurrentClassLogger(); logger.Info("Check the AWS Console CloudWatch Logs console in us-east-1"); logger.Info("to see messages in the log streams for the"); logger.Info("log group NLog.ProgrammaticConfigurationExample"); } static void ConfigureNLog() { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var awsTarget = new AWSTarget() { LogGroup = "NLog.ProgrammaticConfigurationExample", Region = "us-east-1" }; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, awsTarget)); LogManager.Configuration = config; } } }
48
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ProgrammaticConfigurationExample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ProgrammaticConfigurationExample")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bec56974-2caf-4fc0-848f-312ff153174f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-logging-dotnet
aws
C#
using System; using Serilog; using AWS.Logger.SeriLog; using AWS.Logger; namespace SerilogTestCode { class Program { static void Main(string[] args) { AWSLoggerConfig configuration = new AWSLoggerConfig("Serilog.ConfigExample") { Region = "us-east-1" }; var logger = new LoggerConfiguration() .WriteTo.AWSSeriLog(configuration) .CreateLogger(); logger.Information("Hello!"); } } }
25
aws-logging-dotnet
aws
C#
using Serilog; using Microsoft.Extensions.Configuration; namespace SerilogTestCodeFromConfig { class Program { static void Main(string[] args) { // logger configuration reads from appsettings.json var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); logger.Information("Hello!"); } } }
23
aws-logging-dotnet
aws
C#
using Serilog; using Microsoft.Extensions.Configuration; namespace SerilogTestCodeFromConfigRestrictedToMinimumLevel { class Program { static void Main(string[] args) { // logger configuration reads from appsettings.json var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); logger.Information("This should not log since restrictedToMinimumLevel is Error in appsettings.json!"); logger.Error("Hello!"); } } }
24
aws-logging-dotnet
aws
C#
using System; using Microsoft.Extensions.Logging; using AWS.Logger.Core; using System.Text; using System.Collections.Generic; namespace AWS.Logger.AspNetCore { /// <summary> /// Implementation of the Microsoft.Extensions.Logging.ILogger. /// </summary> public class AWSLogger : ILogger { private readonly string _categoryName; private readonly IAWSLoggerCore _core; private readonly Func<string, LogLevel, bool> _filter; private readonly Func<LogLevel, object, Exception, string> _customFormatter; private bool _includeScopes; /// <summary> /// Prefix log messages with scopes created with ILogger.BeginScope /// </summary> public bool IncludeScopes { get { return this._includeScopes; } set { if(value && this.ScopeProvider == NullExternalScopeProvider.Instance) { this.ScopeProvider = new LoggerExternalScopeProvider(); } this._includeScopes = value; } } /// <summary> /// Include log level in log message /// </summary> public bool IncludeLogLevel { get; set; } = Constants.IncludeLogLevelDefault; /// <summary> /// Include category in log message /// </summary> public bool IncludeCategory { get; set; } = Constants.IncludeCategoryDefault; /// <summary> /// Include event id in log message /// </summary> public bool IncludeEventId { get; set; } = Constants.IncludeEventIdDefault; /// <summary> /// Include new line in log message /// </summary> public bool IncludeNewline { get; set; } = Constants.IncludeNewlineDefault; /// <summary> /// Include exception in log message /// </summary> public bool IncludeException { get; set; } = Constants.IncludeExceptionDefault; internal IExternalScopeProvider ScopeProvider { get; set; } = NullExternalScopeProvider.Instance; /// <summary> /// Construct an instance of AWSLogger /// </summary> /// <param name="categoryName">The category name for the logger which can be used for filtering.</param> /// <param name="core">The core logger that is used to send messages to AWS.</param> /// <param name="filter">Filter function that will only allow messages to be sent to AWS if it returns true. If the value is null all messages are sent.</param> /// <param name="customFormatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> public AWSLogger(string categoryName, IAWSLoggerCore core, Func<string, LogLevel, bool> filter, Func<LogLevel, object, Exception, string> customFormatter = null) { _categoryName = categoryName; _core = core; _filter = filter; _customFormatter = customFormatter; // This is done in the constructor to ensure the logic in the setter is run during initialization. this.IncludeScopes = Constants.IncludeScopesDefault; } /// <inheritdoc /> public IDisposable BeginScope<TState>(TState state) { if (state == null) throw new ArgumentNullException(nameof(state)); return ScopeProvider?.Push(state) ?? new NoOpDisposable(); } /// <summary> /// Test to see if the log level is enabled for logging. This is evaluated by running the filter function passed into the constructor. /// </summary> /// <param name="logLevel"></param> /// <returns></returns> public bool IsEnabled(LogLevel logLevel) { if (_filter == null) return true; return _filter(_categoryName, logLevel); } /// <summary> /// Log the message /// </summary> /// <typeparam name="TState"></typeparam> /// <param name="logLevel"></param> /// <param name="eventId"></param> /// <param name="state"></param> /// <param name="exception"></param> /// <param name="formatter"></param> public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) return; string message; if (_customFormatter == null) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); var messageText = formatter(state, exception); // If neither a message nor an exception are provided, don't log anything (there's nothing to log, after all). if (string.IsNullOrEmpty(messageText) && exception == null) return; // Format of the logged text, optional components are in {} // {[LogLevel] }{ Scopes: => }{Category: }{EventId: }MessageText {Exception}{\n} var messageBuilder = new StringBuilder(); Action<string> addToBuilder = token => { if (string.IsNullOrEmpty(token)) return; if (messageBuilder.Length > 0) messageBuilder.Append(" "); messageBuilder.Append(token); }; if (IncludeLogLevel) { addToBuilder($"[{logLevel}]"); } GetScopeInformation(messageBuilder); if (IncludeCategory) { addToBuilder($"{_categoryName}:"); } if (IncludeEventId) { addToBuilder($"[{eventId}]:"); } addToBuilder(messageText); if (IncludeException) { addToBuilder($"{exception}"); } if (IncludeNewline) { messageBuilder.Append(Environment.NewLine); } message = messageBuilder.ToString(); } else { message = _customFormatter(logLevel, state, exception); // If neither a message nor an exception are provided, don't log anything (there's nothing to log, after all). if (string.IsNullOrEmpty(message) && exception == null) return; } _core.AddMessage(message); } private void GetScopeInformation(StringBuilder messageBuilder) { var scopeProvider = ScopeProvider; if (IncludeScopes && scopeProvider != null) { var initialLength = messageBuilder.Length; scopeProvider.ForEachScope((scope, builder) => { if(messageBuilder.Length > 0) { messageBuilder.Append(" "); } messageBuilder.Append(scope.ToString()); }, (messageBuilder)); if (messageBuilder.Length > initialLength) { messageBuilder.Append(" =>"); } } } private class NoOpDisposable : IDisposable { public void Dispose() { } } } }
216
aws-logging-dotnet
aws
C#
using AWS.Logger; using AWS.Logger.AspNetCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Linq; // Same namespace as ILoggingBuilder, to make these extensions appear // without the user needing to including our namespace first. namespace Microsoft.Extensions.Logging { /// <summary> /// ILoggingBuilder extensions /// </summary> public static class AWSLoggerBuilderExtensions { /// <summary> /// Adds the AWS logging provider to the log builder using the configuration specified in the AWSLoggerConfig /// </summary> /// <param name="builder"></param> /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param> /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> /// <returns></returns> public static ILoggingBuilder AddAWSProvider(this ILoggingBuilder builder, AWSLoggerConfig config, Func<LogLevel, object, Exception, string> formatter = null) { // If config is null. Assuming the logger is being activated in a debug environment // and skip adding the provider. We don't want to prevent developers running their application // locally because they don't have access or want to use AWS for their local development. if (config == null) { return builder; } var provider = new AWSLoggerProvider(config, formatter); builder.AddProvider(provider); return builder; } /// <summary> /// Adds the AWS logging provider to the log builder using the configuration specified in the AWSLoggerConfig /// </summary> /// <param name="builder"></param> /// <param name="configSection">Configuration and loglevels on how to connect to AWS and how the log messages should be sent.</param> /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> /// <returns></returns> public static ILoggingBuilder AddAWSProvider(this ILoggingBuilder builder, AWSLoggerConfigSection configSection, Func<LogLevel, object, Exception, string> formatter = null) { // If configSection is null. Assuming the logger is being activated in a debug environment // and skip adding the provider. We don't want to prevent developers running their application // locally because they don't have access or want to use AWS for their local development. if (configSection == null) { return builder; } var provider = new AWSLoggerProvider(configSection, formatter); builder.AddProvider(provider); return builder; } /// <summary> /// Adds the AWS logging provider to the log builder by looking up configuration information from the IConfiguration added to the service collection. /// If configuration information can not be found then the AWS logging provider will not be added. /// </summary> /// <param name="builder"></param> /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> /// <returns></returns> public static ILoggingBuilder AddAWSProvider(this ILoggingBuilder builder, Func<LogLevel, object, Exception, string> formatter = null) { var configuration = GetConfiguration(builder.Services); // If configuration or configSection is null. Assuming the logger is being activated in a debug environment // and skip adding the provider. We don't want to prevent developers running their application // locally because they don't have access or want to use AWS for their local development. if (configuration == null) { return builder; } var configSection = configuration.GetAWSLoggingConfigSection(); if (configSection == null) { return builder; } return AddAWSProvider(builder, configSection, formatter); } private static IConfiguration GetConfiguration(IServiceCollection services) { var serviceDescriptor = services.FirstOrDefault(x => x.ServiceType == typeof(IConfiguration)); if (serviceDescriptor == null) { return null; } var configuration = serviceDescriptor.ImplementationInstance as IConfiguration; if (configuration == null && serviceDescriptor.ImplementationFactory != null) { var provider = services.BuildServiceProvider(); configuration = serviceDescriptor.ImplementationFactory(provider) as IConfiguration; } return configuration; } /// <summary> /// Adds the AWS logging provider to the log builder using the configuration specified in the AWSLoggerConfig /// </summary> /// <param name="builder"></param> /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param> /// <param name="minLevel">The minimum log level for messages to be written.</param> /// <returns></returns> public static ILoggingBuilder AddAWSProvider(this ILoggingBuilder builder, AWSLoggerConfig config, LogLevel minLevel) { var provider = new AWSLoggerProvider(config, minLevel); builder.AddProvider(provider); return builder; } /// <summary> /// Adds the AWS logging provider to the log builder using the configuration specified in the AWSLoggerConfig /// </summary> /// <param name="builder"></param> /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param> /// <param name="filter">A filter function that has the logger category name and log level which can be used to filter messages being sent to AWS.</param> /// <returns></returns> public static ILoggingBuilder AddAWSProvider(this ILoggingBuilder builder, AWSLoggerConfig config, Func<string, LogLevel, bool> filter) { var provider = new AWSLoggerProvider(config, filter); builder.AddProvider(provider); return builder; } } }
137
aws-logging-dotnet
aws
C#
using AWS.Logger; using System; using System.Linq; // Placed in the Microsoft namespaces so that the extension methods are visible whenever the owning namespace // is declared. namespace Microsoft.Extensions.Configuration { /// <summary> /// Extensions methods for IConfiguration to lookup AWS logger configuration /// </summary> public static class ConfigurationSectionExtensions { // Default configuration block on the appsettings.json // Customer's information will be fetched from this block unless otherwise set. private const string DEFAULT_BLOCK = "Logging"; // This library was originally written before logging standarized, or it at least we didn't realize it was standarized, on the "Logging" section in the config. // The library now uses "Logging" as the default section to look for config but to maintain backwards compatibility the package will fallback // AWS.Logging if a log group is not configured in the "Logging" config block". private const string LEGACY_DEFAULT_BLOCK = "AWS.Logging"; /// <summary> /// Loads the AWS Logger Configuration from the ConfigSection /// </summary> /// <param name="configSection">ConfigSection</param> /// <param name="configSectionInfoBlockName">ConfigSection SubPath to load from</param> /// <returns></returns> public static AWSLoggerConfigSection GetAWSLoggingConfigSection(this IConfiguration configSection, string configSectionInfoBlockName = DEFAULT_BLOCK) { var loggerConfigSection = configSection.GetSection(configSectionInfoBlockName); AWSLoggerConfigSection configObj = null; if (loggerConfigSection[AWSLoggerConfigSection.LOG_GROUP] != null) { configObj = new AWSLoggerConfigSection(loggerConfigSection); } // If the code was relying on the default config block and no log group was found then // check the legacy default block. else if(string.Equals(configSectionInfoBlockName, DEFAULT_BLOCK, StringComparison.InvariantCulture)) { loggerConfigSection = configSection.GetSection(LEGACY_DEFAULT_BLOCK); if (loggerConfigSection[AWSLoggerConfigSection.LOG_GROUP] != null) { configObj = new AWSLoggerConfigSection(loggerConfigSection); } } return configObj; } } /// <summary> /// This class stores the configuration section information to connect to AWS and how the messages should be sent and the LogLevel section details /// </summary> public class AWSLoggerConfigSection { /// <summary> /// Configuration options for logging messages to AWS /// </summary> public AWSLoggerConfig Config { get; set; } = new AWSLoggerConfig(); /// <summary> /// Custom LogLevel Filters for <see cref="AWS.Logger.AspNetCore.AWSLoggerProvider"/> /// </summary> public IConfiguration LogLevels { get; set; } = null; /// <summary> /// Gets the <see cref="AWS.Logger.AspNetCore.AWSLogger.IncludeScopes"/> property. This determines if scopes - if they exist - are included in a log message. /// <para> /// The default is false. /// </para> /// </summary> public bool IncludeScopes { get; set; } = AWS.Logger.AspNetCore.Constants.IncludeScopesDefault; /// <summary> /// Gets the <see cref="AWS.Logger.AspNetCore.AWSLogger.IncludeLogLevel"/> property. This determines if log level is included in a log message. /// <para> /// The default is true. /// </para> /// </summary> public bool IncludeLogLevel { get; set; } = AWS.Logger.AspNetCore.Constants.IncludeLogLevelDefault; /// <summary> /// Gets the <see cref="AWS.Logger.AspNetCore.AWSLogger.IncludeCategory"/> property. This determines if category is included in a log message. /// <para> /// The default is true. /// </para> /// </summary> public bool IncludeCategory { get; set; } = AWS.Logger.AspNetCore.Constants.IncludeCategoryDefault; /// <summary> /// Gets the <see cref="AWS.Logger.AspNetCore.AWSLogger.IncludeEventId"/> property. This determines if event id is included in a log message. /// <para> /// The default is false. /// </para> /// </summary> public bool IncludeEventId { get; set; } = AWS.Logger.AspNetCore.Constants.IncludeEventIdDefault; /// <summary> /// Gets the <see cref="AWS.Logger.AspNetCore.AWSLogger.IncludeNewline"/> property. This determines if a new line is added to the end of the log message. /// <para> /// The default is true. /// </para> /// </summary> public bool IncludeNewline { get; set; } = AWS.Logger.AspNetCore.Constants.IncludeNewlineDefault; /// <summary> /// Gets the <see cref="AWS.Logger.AspNetCore.AWSLogger.IncludeException"/> property. This determines if exceptions are included in a log message. /// <para> /// The default is false. /// </para> /// </summary> public bool IncludeException { get; set; } = AWS.Logger.AspNetCore.Constants.IncludeExceptionDefault; internal const string LOG_GROUP = "LogGroup"; internal const string DISABLE_LOG_GROUP_CREATION = "DisableLogGroupCreation"; internal const string REGION = "Region"; internal const string SERVICEURL = "ServiceUrl"; internal const string PROFILE = "Profile"; internal const string PROFILE_LOCATION = "ProfilesLocation"; internal const string BATCH_PUSH_INTERVAL = "BatchPushInterval"; internal const string BATCH_PUSH_SIZE_IN_BYTES = "BatchPushSizeInBytes"; internal const string LOG_LEVEL = "LogLevel"; internal const string MAX_QUEUED_MESSAGES = "MaxQueuedMessages"; internal const string LOG_STREAM_NAME_SUFFIX = "LogStreamNameSuffix"; internal const string LOG_STREAM_NAME_PREFIX = "LogStreamNamePrefix"; internal const string LIBRARY_LOG_FILE_NAME = "LibraryLogFileName"; internal const string LIBRARY_LOG_ERRORS = "LibraryLogErrors"; internal const string FLUSH_TIMEOUT = "FlushTimeout"; private const string INCLUDE_LOG_LEVEL_KEY = "IncludeLogLevel"; private const string INCLUDE_CATEGORY_KEY = "IncludeCategory"; private const string INCLUDE_NEWLINE_KEY = "IncludeNewline"; private const string INCLUDE_EXCEPTION_KEY = "IncludeException"; private const string INCLUDE_EVENT_ID_KEY = "IncludeEventId"; private const string INCLUDE_SCOPES_KEY = "IncludeScopes"; /// <summary> /// Construct an instance of AWSLoggerConfigSection /// </summary> /// <param name="loggerConfigSection">ConfigSection to parse</param> public AWSLoggerConfigSection(IConfiguration loggerConfigSection) { Config.LogGroup = loggerConfigSection[LOG_GROUP]; Config.DisableLogGroupCreation = loggerConfigSection.GetValue<bool>(DISABLE_LOG_GROUP_CREATION); if (loggerConfigSection[REGION] != null) { Config.Region = loggerConfigSection[REGION]; } if (loggerConfigSection[SERVICEURL] != null) { Config.ServiceUrl = loggerConfigSection[SERVICEURL]; } if (loggerConfigSection[PROFILE] != null) { Config.Profile = loggerConfigSection[PROFILE]; } if (loggerConfigSection[PROFILE_LOCATION] != null) { Config.ProfilesLocation = loggerConfigSection[PROFILE_LOCATION]; } if (loggerConfigSection[BATCH_PUSH_INTERVAL] != null) { Config.BatchPushInterval = TimeSpan.FromMilliseconds(Int32.Parse(loggerConfigSection[BATCH_PUSH_INTERVAL])); } if (loggerConfigSection[BATCH_PUSH_SIZE_IN_BYTES] != null) { Config.BatchSizeInBytes = Int32.Parse(loggerConfigSection[BATCH_PUSH_SIZE_IN_BYTES]); } if (loggerConfigSection[MAX_QUEUED_MESSAGES] != null) { Config.MaxQueuedMessages = Int32.Parse(loggerConfigSection[MAX_QUEUED_MESSAGES]); } if (loggerConfigSection[LOG_STREAM_NAME_SUFFIX] != null) { Config.LogStreamNameSuffix = loggerConfigSection[LOG_STREAM_NAME_SUFFIX]; } if (loggerConfigSection[LOG_STREAM_NAME_PREFIX] != null) { Config.LogStreamNamePrefix = loggerConfigSection[LOG_STREAM_NAME_PREFIX]; } if (loggerConfigSection[LIBRARY_LOG_FILE_NAME] != null) { Config.LibraryLogFileName = loggerConfigSection[LIBRARY_LOG_FILE_NAME]; } if (loggerConfigSection[LIBRARY_LOG_ERRORS] != null) { Config.LibraryLogErrors = Boolean.Parse(loggerConfigSection[LIBRARY_LOG_ERRORS]); } if (loggerConfigSection[FLUSH_TIMEOUT] != null) { Config.FlushTimeout = TimeSpan.FromMilliseconds(Int32.Parse(loggerConfigSection[FLUSH_TIMEOUT])); } if (loggerConfigSection[INCLUDE_LOG_LEVEL_KEY] != null) { this.IncludeLogLevel = Boolean.Parse(loggerConfigSection[INCLUDE_LOG_LEVEL_KEY]); } if (loggerConfigSection[INCLUDE_CATEGORY_KEY] != null) { this.IncludeCategory = Boolean.Parse(loggerConfigSection[INCLUDE_CATEGORY_KEY]); } if (loggerConfigSection[INCLUDE_NEWLINE_KEY] != null) { this.IncludeNewline = Boolean.Parse(loggerConfigSection[INCLUDE_NEWLINE_KEY]); } if (loggerConfigSection[INCLUDE_EXCEPTION_KEY] != null) { this.IncludeException = Boolean.Parse(loggerConfigSection[INCLUDE_EXCEPTION_KEY]); } if (loggerConfigSection[INCLUDE_EVENT_ID_KEY] != null) { this.IncludeEventId = Boolean.Parse(loggerConfigSection[INCLUDE_EVENT_ID_KEY]); } if (loggerConfigSection[INCLUDE_SCOPES_KEY] != null) { this.IncludeScopes = Boolean.Parse(loggerConfigSection[INCLUDE_SCOPES_KEY]); } var logLevels = loggerConfigSection.GetSection(LOG_LEVEL); if (logLevels?.GetChildren().Any() == true) { this.LogLevels = logLevels; } } } }
230
aws-logging-dotnet
aws
C#
using AWS.Logger; using AWS.Logger.AspNetCore; using Microsoft.Extensions.Configuration; using System; namespace Microsoft.Extensions.Logging { /// <summary> /// Extensions methods for ILoggerFactory to add the AWS logging provider /// </summary> public static class AWSLoggerFactoryExtensions { /// <summary> /// Adds the AWS logging provider to the log factory using the configuration specified in the AWSLoggerConfig /// </summary> /// <param name="factory"></param> /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param> /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> /// <returns></returns> public static ILoggerFactory AddAWSProvider(this ILoggerFactory factory, AWSLoggerConfig config, Func<LogLevel, object, Exception, string> formatter = null) { // If config is null. Assuming the logger is being activated in a debug environment // and skip adding the provider. We don't want to prevent developers running their application // locally because they don't have access or want to use AWS for their local development. if (config == null) { factory.CreateLogger("AWS.Logging.AspNetCore").LogWarning("AWSLoggerConfig is null, skipping adding AWS Logging provider."); return factory; } var provider = new AWSLoggerProvider(config, formatter); factory.AddProvider(provider); return factory; } /// <summary> /// Adds the AWS logging provider to the log factory using the configuration specified in the AWSLoggerConfig /// </summary> /// <param name="factory"></param> /// <param name="configSection">Configuration and loglevels on how to connect to AWS and how the log messages should be sent.</param> /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> /// <returns></returns> public static ILoggerFactory AddAWSProvider(this ILoggerFactory factory, AWSLoggerConfigSection configSection, Func<LogLevel, object, Exception, string> formatter = null) { // If configSection is null. Assuming the logger is being activated in a debug environment // and skip adding the provider. We don't want to prevent developers running their application // locally because they don't have access or want to use AWS for their local development. if (configSection == null) { factory.CreateLogger("AWS.Logging.AspNetCore").LogWarning("AWSLoggerConfigSection is null. LogGroup is likely not configured in config files. Skipping adding AWS Logging provider."); return factory; } var provider = new AWSLoggerProvider(configSection, formatter); factory.AddProvider(provider); return factory; } /// <summary> /// Adds the AWS logging provider to the log factory using the configuration specified in the AWSLoggerConfig /// </summary> /// <param name="factory"></param> /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param> /// <param name="minLevel">The minimum log level for messages to be written.</param> /// <returns></returns> public static ILoggerFactory AddAWSProvider(this ILoggerFactory factory, AWSLoggerConfig config, LogLevel minLevel) { var provider = new AWSLoggerProvider(config, minLevel); factory.AddProvider(provider); return factory; } /// <summary> /// Adds the AWS logging provider to the log factory using the configuration specified in the AWSLoggerConfig /// </summary> /// <param name="factory"></param> /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param> /// <param name="filter">A filter function that has the logger category name and log level which can be used to filter messages being sent to AWS.</param> /// <returns></returns> public static ILoggerFactory AddAWSProvider(this ILoggerFactory factory, AWSLoggerConfig config, Func<string, LogLevel, bool> filter) { var provider = new AWSLoggerProvider(config, filter); factory.AddProvider(provider); return factory; } } }
88
aws-logging-dotnet
aws
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using AWS.Logger.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace AWS.Logger.AspNetCore { /// <summary> /// Implementation of the ILoggerProvider which is used to create instances of ILogger. /// </summary> public class AWSLoggerProvider : ILoggerProvider, ISupportExternalScope { private readonly ConcurrentDictionary<string, AWSLogger> _loggers = new ConcurrentDictionary<string, AWSLogger>(); private IExternalScopeProvider _scopeProvider; private readonly IAWSLoggerCore _core; private readonly AWSLoggerConfigSection _configSection; private readonly Func<LogLevel, object, Exception, string> _customFormatter; private Func<string, LogLevel, bool> _customFilter; // Constants private const string DEFAULT_CATEGORY_NAME = "Default"; /// <summary> /// Creates the logging provider with the configuration information to connect to AWS and how the messages should be sent. /// </summary> /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param> /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> public AWSLoggerProvider(AWSLoggerConfig config, Func<LogLevel, object, Exception, string> formatter = null) : this(config, LogLevel.Trace, formatter) { } /// <summary> /// Creates the logging provider with the configuration information to connect to AWS and how the messages should be sent. /// </summary> /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param> /// <param name="minLevel">The minimum log level for messages to be written.</param> /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> public AWSLoggerProvider(AWSLoggerConfig config, LogLevel minLevel, Func<LogLevel, object, Exception, string> formatter = null) : this(config, CreateLogLevelFilter(minLevel), formatter) { } /// <summary> /// Creates the logging provider with the configuration information to connect to AWS and how the messages should be sent. /// </summary> /// <param name="config">Configuration on how to connect to AWS and how the log messages should be sent.</param> /// <param name="filter">A filter function that has the logger category name and log level which can be used to filter messages being sent to AWS.</param> /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> public AWSLoggerProvider(AWSLoggerConfig config, Func<string, LogLevel, bool> filter, Func<LogLevel, object, Exception, string> formatter = null) { _scopeProvider = NullExternalScopeProvider.Instance; _core = new AWSLoggerCore(config, "ILogger"); _customFilter = filter; _customFormatter = formatter; } /// <summary> /// Creates the logging provider with the configuration section information to connect to AWS and how the messages should be sent. Also contains the LogLevel details /// </summary> /// <param name="configSection">Contains configuration on how to connect to AWS and how the log messages should be sent. Also contains the LogeLevel details based upon which the filter values would be set</param> /// <param name="formatter">A custom formatter which accepts a LogLevel, a state, and an exception and returns the formatted log message.</param> public AWSLoggerProvider(AWSLoggerConfigSection configSection, Func<LogLevel, object, Exception, string> formatter) : this(configSection) { _customFormatter = formatter; } /// <summary> /// Creates the logging provider with the configuration section information to connect to AWS and how the messages should be sent. Also contains the LogLevel details /// </summary> /// <param name="configSection">Contains configuration on how to connect to AWS and how the log messages should be sent. Also contains the LogeLevel details based upon which the filter values would be set</param> public AWSLoggerProvider(AWSLoggerConfigSection configSection) { _scopeProvider = configSection.IncludeScopes ? new LoggerExternalScopeProvider() : NullExternalScopeProvider.Instance; _configSection = configSection; _core = new AWSLoggerCore(_configSection.Config, "ILogger"); } /// <summary> /// Called by the ILoggerFactory to create an ILogger /// </summary> /// <param name="categoryName">The category name of the logger which can be used for filtering.</param> /// <returns></returns> public ILogger CreateLogger(string categoryName) { var name = string.IsNullOrEmpty(categoryName) ? DEFAULT_CATEGORY_NAME : categoryName; var filter = _customFilter; if (_configSection != null && filter == null) { filter = CreateConfigSectionFilter(_configSection.LogLevels, name); } return _loggers.GetOrAdd(name, loggerName => new AWSLogger(categoryName, _core, filter, _customFormatter) { ScopeProvider = _scopeProvider, IncludeScopes = _configSection?.IncludeScopes ?? Constants.IncludeScopesDefault, IncludeLogLevel = _configSection?.IncludeLogLevel ?? Constants.IncludeLogLevelDefault, IncludeCategory = _configSection?.IncludeCategory ?? Constants.IncludeCategoryDefault, IncludeEventId = _configSection?.IncludeEventId ?? Constants.IncludeEventIdDefault, IncludeNewline = _configSection?.IncludeNewline ?? Constants.IncludeNewlineDefault, IncludeException = _configSection?.IncludeException ?? Constants.IncludeExceptionDefault }); } /// <summary> /// Disposes the provider. /// </summary> public void Dispose() { _core.Close(); } /// <summary> /// Creates a simple filter based on a minimum log level. /// </summary> /// <param name="minLevel"></param> /// <returns></returns> public static Func<string, LogLevel, bool> CreateLogLevelFilter(LogLevel minLevel) { return (category, logLevel) => logLevel >= minLevel; } /// <summary> /// Creates a filter based upon the prefix of the category name given to the logger /// </summary> /// <param name="logLevels">Contains the configuration details of the Log levels</param> /// <param name="categoryName">Identifier name that is given to a logger</param> /// <returns></returns> public static Func<string, LogLevel, bool> CreateConfigSectionFilter(IConfiguration logLevels, string categoryName) { string name = categoryName; foreach (var prefix in GetKeyPrefixes(name)) { LogLevel level; if (TryGetSwitch(prefix, logLevels, out level)) { return (n, l) => l >= level; } } return (n, l) => false; } /// <summary> /// This method fetches the prefix name from the supplied category name of the logger. In case of no prefix match "Default" value is returned. /// </summary> /// <param name="name">The category name parameter given to a logger</param> /// <returns></returns> private static IEnumerable<string> GetKeyPrefixes(string name) { while (!string.IsNullOrEmpty(name)) { yield return name; var lastIndexOfDot = name.LastIndexOf('.'); if (lastIndexOfDot == -1) { yield return "Default"; break; } name = name.Substring(0, lastIndexOfDot); } } /// <summary> /// This method gets the prefix name from the function CreateConfigSectionFilter and checks if there is a filter that matches. /// </summary> /// <param name="name">The prefix name supplied by the function CreateConfigSectionFilter. The filter matching operation would be based upon this supplied value. </param> /// <param name="logLevels">The Configuration section supplied by the user that deals with the logLevels.</param> /// <param name="level">The LogLevel that was found to be a match.</param> /// <returns></returns> public static bool TryGetSwitch(string name, IConfiguration logLevels, out LogLevel level) { var switches = logLevels; if (switches == null) { level = LogLevel.Trace; return true; } var value = switches[name]; if (string.IsNullOrEmpty(value)) { level = LogLevel.None; return false; } else if (Enum.TryParse<LogLevel>(value, out level)) { return true; } else { var message = $"Configuration value '{value}' for category '{name}' is not supported."; throw new InvalidOperationException(message); } } /// <inheritdoc /> public void SetScopeProvider(IExternalScopeProvider scopeProvider) { _scopeProvider = scopeProvider; foreach (var logger in _loggers) { logger.Value.ScopeProvider = _scopeProvider; } } } }
213
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace AWS.Logger.AspNetCore { internal class Constants { internal const bool IncludeScopesDefault = false; internal const bool IncludeLogLevelDefault = true; internal const bool IncludeCategoryDefault = true; internal const bool IncludeEventIdDefault = false; internal const bool IncludeNewlineDefault = true; internal const bool IncludeExceptionDefault = true; } }
17
aws-logging-dotnet
aws
C#
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions.Internal; using System; namespace AWS.Logger.AspNetCore { /// <summary> /// Scope provider that does nothing. /// </summary> internal class NullExternalScopeProvider : IExternalScopeProvider { private NullExternalScopeProvider() { } /// <summary> /// Returns a cached instance of <see cref="NullExternalScopeProvider"/>. /// </summary> public static IExternalScopeProvider Instance { get; } = new NullExternalScopeProvider(); /// <inheritdoc /> void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } /// <inheritdoc /> IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } }
33
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ec54d8db-9ecc-4026-9d00-bdde02af650a")]
11
aws-logging-dotnet
aws
C#
using System; using Amazon.Runtime; namespace AWS.Logger { /// <summary> /// This class contains all the configuration options for logging messages to AWS. As messages from the application are /// sent to the logger they are queued up in a batch. The batch will be sent when either BatchPushInterval or BatchSizeInBytes /// are exceeded. /// /// <para> /// AWS Credentials are determined using the following steps. /// 1) If the Credentials property is set /// 2) If the Profile property is set and the can be found /// 3) Use the AWS SDK for .NET fall back mechanism to find enviroment credentials. /// </para> /// </summary> public class AWSLoggerConfig : IAWSLoggerConfig { private int batchSizeInBytes = 102400; #region Public Properties /// <summary> /// Gets and sets the LogGroup property. This is the name of the CloudWatch Logs group where /// streams will be created and log messages written to. /// </summary> public string LogGroup { get; set; } /// <summary> /// Determines whether or not to create a new Log Group, if the one specified by <see cref="LogGroup"/> doesn't already exist /// If false (the default), the Log Group is created if it doesn't already exist. This requires logs:DescribeLogGroups /// permission to determine if the group exists, and logs:CreateLogGroup permission to create the group if it doesn't already exist. /// If true, creation of Log Groups is disabled. Logging functions only if the specified log group already exists. /// When creation of log groups is disabled, logs:DescribeLogGroups permission is NOT required. /// </summary> public bool DisableLogGroupCreation { get; set; } /// <summary> /// Gets and sets the Profile property. The profile is used to look up AWS credentials in the profile store. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> public string Profile { get; set; } /// <summary> /// Gets and sets the ProfilesLocation property. If this is not set the default profile store is used by the AWS SDK for .NET /// to look up credentials. This is most commonly used when you are running an application of on-priemse under a service account. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> public string ProfilesLocation { get; set; } /// <summary> /// Gets and sets the Credentials property. These are the AWS credentials used by the AWS SDK for .NET to make service calls. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> public AWSCredentials Credentials { get; set; } /// <summary> /// Gets and sets the Region property. This is the AWS Region that will be used for CloudWatch Logs. If this is not /// the AWS SDK for .NET will use its fall back logic to try and determine the region through environment variables and EC2 instance metadata. /// If the Region is not set and no region is found by the SDK's fall back logic then an exception will be thrown. /// </summary> public string Region { get; set; } /// <summary> /// Gets and sets of the ServiceURL property. This is an optional property; change /// it only if you want to try a different service endpoint. Ex. for LocalStack /// </summary> public string ServiceUrl { get; set; } /// <summary> /// Gets and sets the BatchPushInterval property. For performance the log messages are sent to AWS in batch sizes. BatchPushInterval /// dictates the frequency of when batches are sent. If either BatchPushInterval or BatchSizeInBytes are exceeded the batch will be sent. /// <para> /// The default is 3 seconds. /// </para> /// </summary> public TimeSpan BatchPushInterval { get; set; } = TimeSpan.FromMilliseconds(3000); /// <summary> /// Gets and sets the BatchSizeInBytes property. For performance the log messages are sent to AWS in batch sizes. BatchSizeInBytes /// dictates the total size of the batch in bytes when batches are sent. If either BatchPushInterval or BatchSizeInBytes are exceeded the batch will be sent. /// <para> /// The default is 100 Kilobytes. /// </para> /// </summary> public int BatchSizeInBytes { get { return batchSizeInBytes; } set { if (value > Math.Pow(1024, 2)) { throw new ArgumentException("The events batch size cannot exeed 1MB. https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html"); } batchSizeInBytes = value; } } /// <summary> /// Gets and sets the MaxQueuedMessages property. This specifies the maximum number of log messages that could be stored in-memory. MaxQueuedMessages /// dictates the total number of log messages that can be stored in-memory. If this is exceeded, incoming log messages will be dropped. /// <para> /// The default is 10000. /// </para> /// </summary> public int MaxQueuedMessages { get; set; } = 10000; /// <summary> /// Internal MonitorSleepTime property. This specifies the timespan after which the Monitor wakes up. MonitorSleepTime /// dictates the timespan after which the Monitor checks the size and time constarint on the batch log event and the existing in-memory buffer for new messages. /// <para> /// The value is 500 Milliseconds. /// </para> /// </summary> internal TimeSpan MonitorSleepTime = TimeSpan.FromMilliseconds(500); #endregion /// <summary> /// Default Constructor /// </summary> public AWSLoggerConfig() { } /// <summary> /// Construct instance and sets the LogGroup /// </summary> /// <param name="logGroup">The CloudWatch Logs log group.</param> public AWSLoggerConfig(string logGroup) { LogGroup = logGroup; } /// <summary> /// Gets and sets the LogStreamNameSuffix property. The LogStreamName consists of an optional user-defined LogStreamNamePrefix (that can be set here) /// followed by a DateTimeStamp as the prefix, and a user defined suffix value /// The LogstreamName then follows the pattern '[LogStreamNamePrefix]-[DateTime.Now.ToString("yyyy/MM/ddTHH.mm.ss")]-[LogStreamNameSuffix]' /// <para> /// The default is new a Guid. /// </para> /// </summary> public string LogStreamNameSuffix { get; set; } = Guid.NewGuid().ToString(); /// <summary> /// Gets and sets the LogStreamNamePrefix property. The LogStreamName consists of an optional user-defined LogStreamNamePrefix (that can be set here) /// followed by a DateTimeStamp as the prefix, and a user defined suffix value /// The LogstreamName then follows the pattern '[LogStreamNamePrefix]-[DateTime.Now.ToString("yyyy/MM/ddTHH.mm.ss")]-[LogStreamNameSuffix]' /// <para> /// The default is an empty string. /// </para> /// </summary> public string LogStreamNamePrefix { get; set; } = string.Empty; /// <summary> /// Gets and sets the LibraryLogErrors property. This is the boolean value of whether or not you would like this library to log logging errors. /// <para> /// The default is "true". /// </para> /// </summary> public bool LibraryLogErrors { get; set; } = true; /// <summary> /// Gets and sets the LibraryLogFileName property. This is the name of the file into which errors from the AWS.Logger.Core library will be written into. /// <para> /// The default is "aws-logger-errors.txt". /// </para> /// </summary> public string LibraryLogFileName { get; set; } = "aws-logger-errors.txt"; /// <summary> /// Gets the FlushTimeout property. The value is in milliseconds. When performing a flush of the in-memory queue this is the maximum period of time allowed to send the remaining /// messages before it will be aborted. If this is exceeded, incoming log messages will be dropped. /// <para> /// The default is 30000 milliseconds. /// </para> /// </summary> public TimeSpan FlushTimeout { get; set; } = TimeSpan.FromMilliseconds(30000); } }
189
aws-logging-dotnet
aws
C#
using System; using Amazon.Runtime; namespace AWS.Logger { /// <summary> /// Configuration options for logging messages to AWS CloudWatch Logs /// </summary> public interface IAWSLoggerConfig { /// <summary> /// Gets the LogGroup property. This is the name of the CloudWatch Logs group where /// streams will be created and log messages written to. /// </summary> string LogGroup { get; } /// <summary> /// Determines whether or not to create a new Log Group, if the one specified by <see cref="LogGroup"/> doesn't already exist /// If false (the default), the Log Group is created if it doesn't already exist. This requires logs:DescribeLogGroups /// permission to determine if the group exists, and logs:CreateLogGroup permission to create the group if it doesn't already exist. /// If true, creation of Log Groups is disabled. Logging functions only if the specified log group already exists. /// When creation of log groups is disabled, logs:DescribeLogGroups permission is NOT required. /// </summary> bool DisableLogGroupCreation { get; set; } /// <summary> /// Gets the Profile property. The profile is used to look up AWS credentials in the profile store. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> string Profile { get; } /// <summary> /// Gets the ProfilesLocation property. If this is not set the default profile store is used by the AWS SDK for .NET /// to look up credentials. This is most commonly used when you are running an application of on-priemse under a service account. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> string ProfilesLocation { get; } /// <summary> /// Gets the Credentials property. These are the AWS credentials used by the AWS SDK for .NET to make service calls. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> AWSCredentials Credentials { get; } /// <summary> /// Gets the Region property. This is the AWS Region that will be used for CloudWatch Logs. If this is not /// the AWS SDK for .NET will use its fall back logic to try and determine the region through environment variables and EC2 instance metadata. /// If the Region is not set and no region is found by the SDK's fall back logic then an exception will be thrown. /// </summary> string Region { get; } /// <summary> /// Gets and sets of the ServiceURL property. This is an optional property; change /// it only if you want to try a different service endpoint. Ex. for LocalStack /// </summary> string ServiceUrl { get; } /// <summary> /// Gets the BatchPushInterval property. For performance the log messages are sent to AWS in batch sizes. BatchPushInterval /// dictates the frequency of when batches are sent. If either BatchPushInterval or BatchSizeInBytes are exceeded the batch will be sent. /// <para> /// The default is 3 seconds. /// </para> /// </summary> TimeSpan BatchPushInterval { get; } /// <summary> /// Gets the BatchSizeInBytes property. For performance the log messages are sent to AWS in batch sizes. BatchSizeInBytes /// dictates the total size of the batch in bytes when batches are sent. If either BatchPushInterval or BatchSizeInBytes are exceeded the batch will be sent. /// <para> /// The default is 100 Kilobytes. /// </para> /// </summary> int BatchSizeInBytes { get; } /// <summary> /// Gets and sets the MaxQueuedMessages property. This specifies the maximum number of log messages that could be stored in-memory. MaxQueuedMessages /// dictates the total number of log messages that can be stored in-memory. If this is exceeded, incoming log messages will be dropped. /// <para> /// The default is 10000. /// </para> /// </summary> int MaxQueuedMessages { get; } /// <summary> /// Gets and sets the LogStreamNameSuffix property. The LogStreamName consists of an optional user-defined LogStreamNamePrefix (that can be set here) /// followed by a DateTimeStamp as the prefix, and a user defined suffix value /// The LogstreamName then follows the pattern '[LogStreamNamePrefix]-[DateTime.Now.ToString("yyyy/MM/ddTHH.mm.ss")]-[LogStreamNameSuffix]' /// <para> /// The default is new a Guid. /// </para> /// </summary> string LogStreamNameSuffix { get; } /// <summary> /// Gets and sets the LogStreamNamePrefix property. The LogStreamName consists of an optional user-defined LogStreamNamePrefix (that can be set here) /// followed by a DateTimeStamp as the prefix, and a user defined suffix value /// The LogstreamName then follows the pattern '[LogStreamNamePrefix]-[DateTime.Now.ToString("yyyy/MM/ddTHH.mm.ss")]-[LogStreamNameSuffix]' /// <para> /// The default is an empty string. /// </para> /// </summary> string LogStreamNamePrefix { get; set; } /// <summary> /// Gets and sets the LibraryLogErrors property. This is the boolean value of whether or not you would like this library to log logging errors. /// <para> /// The default is "true". /// </para> /// </summary> bool LibraryLogErrors { get; set; } /// <summary> /// Gets and sets the LibraryLogFileName property. This is the name of the file into which errors from the AWS.Logger.Core library will be written into. /// <para> /// The default is going to "aws-logger-errors.txt". /// </para> /// </summary> string LibraryLogFileName { get; } /// <summary> /// Gets the FlushTimeout property. The value is in milliseconds. When performing a flush of the in-memory queue this is the maximum period of time allowed to send the remaining /// messages before it will be aborted. If this is exceeded, incoming log messages will be dropped. /// <para> /// The default is 30000 milliseconds. /// </para> /// </summary> TimeSpan FlushTimeout { get; } } }
137
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Reflection; #if CORECLR using System.Runtime.Loader; #endif using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; namespace AWS.Logger.Core { /// <summary> /// Sends LogEvent messages to CloudWatch Logs /// </summary> public class AWSLoggerCore : IAWSLoggerCore { const int MAX_MESSAGE_SIZE_IN_BYTES = 256000; #region Private Members const string EMPTY_MESSAGE = "\t"; private ConcurrentQueue<InputLogEvent> _pendingMessageQueue = new ConcurrentQueue<InputLogEvent>(); private string _currentStreamName = null; private LogEventBatch _repo = new LogEventBatch(); private CancellationTokenSource _cancelStartSource; private SemaphoreSlim _flushTriggerEvent; private ManualResetEventSlim _flushCompletedEvent; private AWSLoggerConfig _config; private IAmazonCloudWatchLogs _client; private DateTime _maxBufferTimeStamp = new DateTime(); private string _logType; private int _requestCount = 5; /// <summary> /// Minimum interval in minutes between two error messages on in-memory buffer overflow. /// </summary> const double MAX_BUFFER_TIMEDIFF = 5; private readonly static Regex invalid_sequence_token_regex = new Regex(@"The given sequenceToken is invalid. The next expected sequenceToken is: (\d+)"); #endregion /// <summary> /// Alert details from CloudWatch Log Engine /// </summary> public sealed class LogLibraryEventArgs : EventArgs { internal LogLibraryEventArgs(Exception ex) { Exception = ex; } /// <summary> /// Exception Details returned /// </summary> public Exception Exception { get; } /// <summary> /// Service EndPoint Url involved /// </summary> public string ServiceUrl { get; internal set; } } /// <summary> /// Event Notification on alerts from the CloudWatch Log Engine /// </summary> public event EventHandler<LogLibraryEventArgs> LogLibraryAlert; /// <summary> /// Construct an instance of AWSLoggerCore /// </summary> /// <param name="config">Configuration options for logging messages to AWS</param> /// <param name="logType">Logging Provider Name to include in UserAgentHeader</param> public AWSLoggerCore(AWSLoggerConfig config, string logType) { _config = config; _logType = logType; var awsConfig = new AmazonCloudWatchLogsConfig(); if (!string.IsNullOrWhiteSpace(_config.ServiceUrl)) { var serviceUrl = _config.ServiceUrl.Trim(); awsConfig.ServiceURL = serviceUrl; if (serviceUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { awsConfig.UseHttp = true; } } else { if (!string.IsNullOrEmpty(_config.Region)) { awsConfig.RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName(_config.Region); } } var credentials = DetermineCredentials(config); _client = new AmazonCloudWatchLogsClient(credentials, awsConfig); ((AmazonCloudWatchLogsClient)this._client).BeforeRequestEvent += ServiceClientBeforeRequestEvent; ((AmazonCloudWatchLogsClient)this._client).ExceptionEvent += ServiceClienExceptionEvent; StartMonitor(); RegisterShutdownHook(); } #if CORECLR private void RegisterShutdownHook() { var currentAssembly = typeof(AWSLoggerCore).GetTypeInfo().Assembly; AssemblyLoadContext.GetLoadContext(currentAssembly).Unloading += this.OnAssemblyLoadContextUnloading; } internal void OnAssemblyLoadContextUnloading(AssemblyLoadContext obj) { this.Close(); } #else private void RegisterShutdownHook() { AppDomain.CurrentDomain.DomainUnload += ProcessExit; AppDomain.CurrentDomain.ProcessExit += ProcessExit; } private void ProcessExit(object sender, EventArgs e) { Close(); } #endif private static AWSCredentials DetermineCredentials(AWSLoggerConfig config) { if (config.Credentials != null) { return config.Credentials; } if (!string.IsNullOrEmpty(config.Profile)) { var credentials = LookupCredentialsFromProfileStore(config); if (credentials != null) return credentials; } return FallbackCredentialsFactory.GetCredentials(); } private static AWSCredentials LookupCredentialsFromProfileStore(AWSLoggerConfig config) { var credentialProfileStore = string.IsNullOrEmpty(config.ProfilesLocation) ? new CredentialProfileStoreChain() : new CredentialProfileStoreChain(config.ProfilesLocation); if (credentialProfileStore.TryGetAWSCredentials(config.Profile, out var credentials)) return credentials; else return null; } /// <inheritdoc /> public void Close() { try { Flush(); _cancelStartSource.Cancel(); } catch (Exception ex) { LogLibraryServiceError(ex); } finally { LogLibraryAlert = null; } } /// <inheritdoc /> public void Flush() { if (_cancelStartSource.IsCancellationRequested) return; if (!_pendingMessageQueue.IsEmpty || !_repo.IsEmpty) { bool lockTaken = false; try { // Ensure only one thread executes the flush operation System.Threading.Monitor.TryEnter(_flushTriggerEvent, ref lockTaken); if (lockTaken) { _flushCompletedEvent.Reset(); if (_flushTriggerEvent.CurrentCount == 0) { _flushTriggerEvent.Release(); // Signal Monitor-Task to start premature flush } else { // Means that the Background Task is busy, and not yet claimed the previous release (Maybe busy with credentials) var serviceUrl = GetServiceUrl(); LogLibraryServiceError(new TimeoutException($"Flush Pending - ServiceURL={serviceUrl}, StreamName={_currentStreamName}, PendingMessages={_pendingMessageQueue.Count}, CurrentBatch={_repo.CurrentBatchMessageCount}"), serviceUrl); } } // Waiting for Monitor-Task to complete flush if (!_flushCompletedEvent.Wait(_config.FlushTimeout, _cancelStartSource.Token)) { var serviceUrl = GetServiceUrl(); LogLibraryServiceError(new TimeoutException($"Flush Timeout - ServiceURL={serviceUrl}, StreamName={_currentStreamName}, PendingMessages={_pendingMessageQueue.Count}, CurrentBatch={_repo.CurrentBatchMessageCount}"), serviceUrl); } } finally { if (lockTaken) System.Threading.Monitor.Exit(_flushTriggerEvent); } } } private string GetServiceUrl() { try { _client.Config.Validate(); return _client.Config.DetermineServiceURL() ?? "Undetermined ServiceURL"; } catch (Exception ex) { LogLibraryServiceError(ex, string.Empty); return "Unknown ServiceURL"; } } private void AddSingleMessage(string message) { if (_pendingMessageQueue.Count > _config.MaxQueuedMessages) { if (_maxBufferTimeStamp.AddMinutes(MAX_BUFFER_TIMEDIFF) < DateTime.UtcNow) { message = "The AWS Logger in-memory buffer has reached maximum capacity"; if (_maxBufferTimeStamp == DateTime.MinValue) { LogLibraryServiceError(new System.InvalidOperationException(message)); } _maxBufferTimeStamp = DateTime.UtcNow; _pendingMessageQueue.Enqueue(new InputLogEvent { Timestamp = DateTime.UtcNow, Message = message, }); } } else { _pendingMessageQueue.Enqueue(new InputLogEvent { Timestamp = DateTime.UtcNow, Message = message, }); } } /// <summary> /// A Concurrent Queue is used to store the messages from /// the logger /// </summary> /// <param name="rawMessage">Message to log.</param> public void AddMessage(string rawMessage) { if (string.IsNullOrEmpty(rawMessage)) { rawMessage = EMPTY_MESSAGE; } // Only do the extra work of breaking up the message if the max unicode bytes exceeds the possible size. This is not // an exact measurement since the string is UTF8 but it gives us a chance to skip the extra computation for // typically small messages. if (Encoding.Unicode.GetMaxByteCount(rawMessage.Length) < MAX_MESSAGE_SIZE_IN_BYTES) { AddSingleMessage(rawMessage); } else { var messageParts = BreakupMessage(rawMessage); foreach (var message in messageParts) { AddSingleMessage(message); } } } /// <summary> /// Finalizer to ensure shutdown when forgetting to dispose /// </summary> ~AWSLoggerCore() { if (_cancelStartSource != null) { _cancelStartSource.Dispose(); } } /// <summary> /// Kicks off the Poller Thread to keep tabs on the PutLogEvent request and the /// Concurrent Queue /// </summary> public void StartMonitor() { _flushTriggerEvent = new SemaphoreSlim(0, 1); _flushCompletedEvent = new ManualResetEventSlim(false); _cancelStartSource = new CancellationTokenSource(); Task.Run(async () => { await Monitor(_cancelStartSource.Token); }); } /// <summary> /// Patrolling thread. keeps tab on the PutLogEvent request and the /// Concurrent Queue /// </summary> private async Task Monitor(CancellationToken token) { bool executeFlush = false; while (_currentStreamName == null && !token.IsCancellationRequested) { try { _currentStreamName = await LogEventTransmissionSetup(token).ConfigureAwait(false); } catch (OperationCanceledException ex) { if (!_pendingMessageQueue.IsEmpty) LogLibraryServiceError(ex); if (token.IsCancellationRequested) { _client.Dispose(); return; } } catch (Exception ex) { // We don't want to kill the main monitor loop. We will simply log the error, then continue. // If it is an OperationCancelledException, die LogLibraryServiceError(ex); await Task.Delay(Math.Max(100, DateTime.UtcNow.Second * 10), token); } } while (!token.IsCancellationRequested) { try { while (_pendingMessageQueue.TryDequeue(out var inputLogEvent)) { // See if new message will cause the current batch to violote the size constraint. // If so send the current batch now before adding more to the batch of messages to send. if (_repo.CurrentBatchMessageCount > 0 && _repo.IsSizeConstraintViolated(inputLogEvent.Message)) { await SendMessages(token).ConfigureAwait(false); } _repo.AddMessage(inputLogEvent); } if (_repo.ShouldSendRequest(_config.MaxQueuedMessages) || (executeFlush && !_repo.IsEmpty)) { await SendMessages(token).ConfigureAwait(false); } if (executeFlush) _flushCompletedEvent.Set(); executeFlush = await _flushTriggerEvent.WaitAsync(TimeSpan.FromMilliseconds(_config.MonitorSleepTime.TotalMilliseconds), token); } catch (OperationCanceledException ex) when (!token.IsCancellationRequested) { // Workaround to handle timeouts of .net httpclient // https://github.com/dotnet/corefx/issues/20296 LogLibraryServiceError(ex); } catch (OperationCanceledException ex) { if (!token.IsCancellationRequested || !_repo.IsEmpty || !_pendingMessageQueue.IsEmpty) LogLibraryServiceError(ex); _client.Dispose(); return; } catch (Exception ex) { // We don't want to kill the main monitor loop. We will simply log the error, then continue. // If it is an OperationCancelledException, die LogLibraryServiceError(ex); } } } /// <summary> /// Method to transmit the PutLogEvent Request /// </summary> /// <param name="token"></param> /// <returns></returns> private async Task SendMessages(CancellationToken token) { try { //Make sure the log events are in the right order. _repo._request.LogEvents.Sort((ev1, ev2) => ev1.Timestamp.CompareTo(ev2.Timestamp)); var response = await _client.PutLogEventsAsync(_repo._request, token).ConfigureAwait(false); _repo.Reset(response.NextSequenceToken); _requestCount = 5; } catch (InvalidSequenceTokenException ex) { //In case the NextSequenceToken is invalid for the last sent message, a new stream would be //created for the said application. LogLibraryServiceError(ex); if (_requestCount > 0) { _requestCount--; var regexResult = invalid_sequence_token_regex.Match(ex.Message); if (regexResult.Success) { _repo._request.SequenceToken = regexResult.Groups[1].Value; await SendMessages(token).ConfigureAwait(false); } } else { _currentStreamName = await LogEventTransmissionSetup(token).ConfigureAwait(false); } } catch (ResourceNotFoundException ex) { // The specified log stream does not exist. Refresh or create new stream. LogLibraryServiceError(ex); _currentStreamName = await LogEventTransmissionSetup(token).ConfigureAwait(false); } } /// <summary> /// Creates and Allocates resources for message trasnmission /// </summary> /// <returns></returns> private async Task<string> LogEventTransmissionSetup(CancellationToken token) { string serviceURL = GetServiceUrl(); if (!_config.DisableLogGroupCreation) { var logGroupResponse = await _client.DescribeLogGroupsAsync(new DescribeLogGroupsRequest { LogGroupNamePrefix = _config.LogGroup }, token).ConfigureAwait(false); if (!IsSuccessStatusCode(logGroupResponse)) { LogLibraryServiceError(new System.Net.WebException($"Lookup LogGroup {_config.LogGroup} returned status: {logGroupResponse.HttpStatusCode}"), serviceURL); } if (logGroupResponse.LogGroups.FirstOrDefault(x => string.Equals(x.LogGroupName, _config.LogGroup, StringComparison.Ordinal)) == null) { var createGroupResponse = await _client.CreateLogGroupAsync(new CreateLogGroupRequest { LogGroupName = _config.LogGroup }, token).ConfigureAwait(false); if (!IsSuccessStatusCode(createGroupResponse)) { LogLibraryServiceError(new System.Net.WebException($"Create LogGroup {_config.LogGroup} returned status: {createGroupResponse.HttpStatusCode}"), serviceURL); } } } var currentStreamName = GenerateStreamName(_config); var streamResponse = await _client.CreateLogStreamAsync(new CreateLogStreamRequest { LogGroupName = _config.LogGroup, LogStreamName = currentStreamName }, token).ConfigureAwait(false); if (!IsSuccessStatusCode(streamResponse)) { LogLibraryServiceError(new System.Net.WebException($"Create LogStream {currentStreamName} for LogGroup {_config.LogGroup} returned status: {streamResponse.HttpStatusCode}"), serviceURL); } _repo = new LogEventBatch(_config.LogGroup, currentStreamName, Convert.ToInt32(_config.BatchPushInterval.TotalSeconds), _config.BatchSizeInBytes); return currentStreamName; } /// <summary> /// Generate a logstream name /// </summary> /// <returns>logstream name that ALWAYS includes a unique date-based segment</returns> public static string GenerateStreamName(IAWSLoggerConfig config) { var streamName = new StringBuilder(); var prefix = config.LogStreamNamePrefix; if (!string.IsNullOrEmpty(prefix)) { streamName.Append(prefix); streamName.Append(" - "); } streamName.Append(DateTime.Now.ToString("yyyy/MM/ddTHH.mm.ss")); var suffix = config.LogStreamNameSuffix; if (!string.IsNullOrEmpty(suffix)) { streamName.Append(" - "); streamName.Append(suffix); } return streamName.ToString(); } private static bool IsSuccessStatusCode(AmazonWebServiceResponse serviceResponse) { return (int)serviceResponse.HttpStatusCode >= 200 && (int)serviceResponse.HttpStatusCode <= 299; } /// <summary> /// Break up the message into max parts of 256K. /// </summary> /// <param name="message"></param> /// <returns></returns> public static IList<string> BreakupMessage(string message) { var parts = new List<string>(); var singleCharArray = new char[1]; var encoding = Encoding.UTF8; int byteCount = 0; var sb = new StringBuilder(MAX_MESSAGE_SIZE_IN_BYTES); foreach (var c in message) { singleCharArray[0] = c; byteCount += encoding.GetByteCount(singleCharArray); sb.Append(c); // This could go a couple bytes if (byteCount > MAX_MESSAGE_SIZE_IN_BYTES) { parts.Add(sb.ToString()); sb.Clear(); byteCount = 0; } } if (sb.Length > 0) { parts.Add(sb.ToString()); } return parts; } /// <summary> /// Class to handle PutLogEvent request and associated parameters. /// Also has the requisite checks to determine when the object is ready for Transmission. /// </summary> private class LogEventBatch { public TimeSpan TimeIntervalBetweenPushes { get; private set; } public int MaxBatchSize { get; private set; } public bool ShouldSendRequest(int maxQueuedEvents) { if (_request.LogEvents.Count == 0) return false; if (_nextPushTime < DateTime.UtcNow) return true; if (maxQueuedEvents <= _request.LogEvents.Count) return true; return false; } int _totalMessageSize { get; set; } DateTime _nextPushTime; public PutLogEventsRequest _request = new PutLogEventsRequest(); public LogEventBatch(string logGroupName, string streamName, int timeIntervalBetweenPushes, int maxBatchSize) { _request.LogGroupName = logGroupName; _request.LogStreamName = streamName; TimeIntervalBetweenPushes = TimeSpan.FromSeconds(timeIntervalBetweenPushes); MaxBatchSize = maxBatchSize; Reset(null); } public LogEventBatch() { } public int CurrentBatchMessageCount { get { return this._request.LogEvents.Count; } } public bool IsEmpty => _request.LogEvents.Count == 0; public bool IsSizeConstraintViolated(string message) { Encoding unicode = Encoding.Unicode; int prospectiveLength = _totalMessageSize + unicode.GetMaxByteCount(message.Length); if (MaxBatchSize < prospectiveLength) return true; return false; } public void AddMessage(InputLogEvent ev) { Encoding unicode = Encoding.Unicode; _totalMessageSize += unicode.GetMaxByteCount(ev.Message.Length); _request.LogEvents.Add(ev); } public void Reset(string SeqToken) { _request.LogEvents.Clear(); _totalMessageSize = 0; _request.SequenceToken = SeqToken; _nextPushTime = DateTime.UtcNow.Add(TimeIntervalBetweenPushes); } } const string UserAgentHeader = "User-Agent"; void ServiceClientBeforeRequestEvent(object sender, RequestEventArgs e) { var args = e as Amazon.Runtime.WebServiceRequestEventArgs; if (args == null || !args.Headers.ContainsKey(UserAgentHeader)) return; args.Headers[UserAgentHeader] = args.Headers[UserAgentHeader] + " AWSLogger/" + _logType; } void ServiceClienExceptionEvent(object sender, ExceptionEventArgs e) { var eventArgs = e as WebServiceExceptionEventArgs; if (eventArgs?.Exception != null) LogLibraryServiceError(eventArgs?.Exception, eventArgs.Endpoint?.ToString()); else LogLibraryServiceError(new System.Net.WebException(e.GetType().ToString())); } private void LogLibraryServiceError(Exception ex, string serviceUrl = null) { LogLibraryAlert?.Invoke(this, new LogLibraryEventArgs(ex) { ServiceUrl = serviceUrl ?? GetServiceUrl() }); if (!string.IsNullOrEmpty(_config.LibraryLogFileName) && _config.LibraryLogErrors) { LogLibraryError(ex, _config.LibraryLogFileName); } } /// <summary> /// Write Exception details to the file specified with the filename /// </summary> public static void LogLibraryError(Exception ex, string LibraryLogFileName) { try { using (StreamWriter w = File.AppendText(LibraryLogFileName)) { w.WriteLine("Log Entry : "); w.WriteLine("{0}", DateTime.Now.ToString()); w.WriteLine(" :"); w.WriteLine(" :{0}", ex.ToString()); w.WriteLine("-------------------------------"); } } catch (Exception e) { Console.WriteLine("Exception caught when writing error log to file" + e.ToString()); } } } }
689
aws-logging-dotnet
aws
C#
namespace AWS.Logger.Core { /// <summary> /// Interface for sending messages to CloudWatch Logs /// </summary> public interface IAWSLoggerCore { /// <summary> /// Flushes all pending messages /// </summary> void Flush(); /// <summary> /// Flushes and Closes the background task /// </summary> void Close(); /// <summary> /// Sends message to CloudWatch Logs /// </summary> /// <param name="message">Message to log.</param> void AddMessage(string message); /// <summary> /// Start background task for sending messages to CloudWatch Logs /// </summary> void StartMonitor(); } }
30
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d99fe4cd-0566-43f0-a339-b6fd7e603d10")]
10
aws-logging-dotnet
aws
C#
using System; using log4net.Appender; using log4net.Core; using Amazon.Runtime; using AWS.Logger.Core; namespace AWS.Logger.Log4net { /// <summary> /// A Log4net appender that sends logging messages to AWS. /// </summary> public class AWSAppender : AppenderSkeleton, IAWSLoggerConfig { AWSLoggerConfig _config = new AWSLoggerConfig(); AWSLoggerCore _core = null; /// <summary> /// Default Constructor /// </summary> public AWSAppender() { } /// <summary> /// Gets and sets the LogGroup property. This is the name of the CloudWatch Logs group where /// streams will be created and log messages written to. /// </summary> public string LogGroup { get { return _config.LogGroup; } set { _config.LogGroup = value; } } /// <summary> /// Determines whether or not to create a new Log Group, if the one specified by <see cref="LogGroup"/> doesn't already exist /// <seealso cref="AWSLoggerConfig.DisableLogGroupCreation"/> /// </summary> public bool DisableLogGroupCreation { get { return _config.DisableLogGroupCreation; } set { _config.DisableLogGroupCreation = value; } } /// <summary> /// Gets and sets the Profile property. The profile is used to look up AWS credentials in the profile store. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> public string Profile { get { return _config.Profile; } set { _config.Profile = value; } } /// <summary> /// Gets and sets the ProfilesLocation property. If this is not set the default profile store is used by the AWS SDK for .NET /// to look up credentials. This is most commonly used when you are running an application of on-priemse under a service account. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> public string ProfilesLocation { get { return _config.ProfilesLocation; } set { _config.ProfilesLocation = value; } } /// <summary> /// Gets and sets the Credentials property. These are the AWS credentials used by the AWS SDK for .NET to make service calls. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> public AWSCredentials Credentials { get { return _config.Credentials; } set { _config.Credentials = value; } } /// <summary> /// Gets and sets the Region property. This is the AWS Region that will be used for CloudWatch Logs. If this is not /// the AWS SDK for .NET will use its fall back logic to try and determine the region through environment variables and EC2 instance metadata. /// If the Region is not set and no region is found by the SDK's fall back logic then an exception will be thrown. /// </summary> public string Region { get { return _config.Region; } set { _config.Region = value; } } /// <summary> /// Gets and sets of the ServiceURL property. This is an optional property; change /// it only if you want to try a different service endpoint. Ex. for LocalStack /// </summary> public string ServiceUrl { get { return _config.ServiceUrl; } set { _config.ServiceUrl = value; } } /// <summary> /// Gets and sets the BatchPushInterval property. For performance the log messages are sent to AWS in batch sizes. BatchPushInterval /// dictates the frequency of when batches are sent. If either BatchPushInterval or BatchSizeInBytes are exceeded the batch will be sent. /// <para> /// The default is 3 seconds. /// </para> /// </summary> public TimeSpan BatchPushInterval { get { return _config.BatchPushInterval; } set { _config.BatchPushInterval = value; } } /// <summary> /// Gets and sets the BatchSizeInBytes property. For performance the log messages are sent to AWS in batch sizes. BatchSizeInBytes /// dictates the total size of the batch in bytes when batches are sent. If either BatchPushInterval or BatchSizeInBytes are exceeded the batch will be sent. /// <para> /// The default is 100 Kilobytes. /// </para> /// </summary> public int BatchSizeInBytes { get { return _config.BatchSizeInBytes; } set { _config.BatchSizeInBytes = value; } } /// <summary> /// Gets and sets the MaxQueuedMessages property. This specifies the maximum number of log messages that could be stored in-memory. MaxQueuedMessages /// dictates the total number of log messages that can be stored in-memory. If this is exceeded, incoming log messages will be dropped. /// <para> /// The default is 10000. /// </para> /// </summary> public int MaxQueuedMessages { get { return _config.MaxQueuedMessages; } set { _config.MaxQueuedMessages = value; } } /// <summary> /// Gets and sets the LogStreamNameSuffix property. The LogStreamName consists of an optional user-defined prefix segment, then a DateTimeStamp as the /// system-defined prefix segment, and a user defined suffix value that can be set using the LogStreamNameSuffix property defined here. /// <para> /// The default is going to a Guid. /// </para> /// </summary> public string LogStreamNameSuffix { get { return _config.LogStreamNameSuffix; } set { _config.LogStreamNameSuffix = value; } } /// <summary> /// Gets and sets the LogStreamNamePrefix property. The LogStreamName consists of an optional user-defined prefix segment (defined here), then a /// DateTimeStamp as the system-defined prefix segment, and a user defined suffix value that can be set using the LogStreamNameSuffix property. /// <para> /// The default will use an empty string for this user-defined portion, meaning the log stream name will start with the system-defined portion of the prefix (yyyy/MM/dd ... ) /// </para> /// </summary> public string LogStreamNamePrefix { get { return _config.LogStreamNamePrefix; } set { _config.LogStreamNamePrefix = value; } } /// <summary> /// Gets and sets the LibraryLogErrors property. This is the boolean value of whether or not you would like this library to log logging errors. /// <para> /// The default is "true". /// </para> /// </summary> public bool LibraryLogErrors { get { return _config.LibraryLogErrors; } set { _config.LibraryLogErrors = value; } } /// <summary> /// Gets and sets the FlushTimeout property. The value is in milliseconds. When performing a flush of the in-memory queue this is the maximum period of time allowed to send the remaining /// messages before it will be aborted. If this is exceeded, incoming log messages will be dropped. /// <para> /// The default is 30000 milliseconds. /// </para> /// </summary> public TimeSpan FlushTimeout { get { return _config.FlushTimeout; } set { _config.FlushTimeout = value; } } /// <summary> /// Gets and sets the LibraryLogFileName property. This is the name of the file into which errors from the AWS.Logger.Core library will be written into. /// <para> /// The default is going to "aws-logger-errors.txt". /// </para> /// </summary> public string LibraryLogFileName { get { return _config.LibraryLogFileName; } set { _config.LibraryLogFileName = value; } } /// <summary> /// Initialize the appender based on the options set. /// </summary> public override void ActivateOptions() { if (_core != null) { _core.Close(); _core = null; } var config = new AWSLoggerConfig(this.LogGroup) { DisableLogGroupCreation = DisableLogGroupCreation, Region = Region, ServiceUrl = ServiceUrl, Credentials = Credentials, Profile = Profile, ProfilesLocation = ProfilesLocation, BatchPushInterval = BatchPushInterval, BatchSizeInBytes = BatchSizeInBytes, MaxQueuedMessages = MaxQueuedMessages, LogStreamNameSuffix = LogStreamNameSuffix, LogStreamNamePrefix = LogStreamNamePrefix, LibraryLogErrors = LibraryLogErrors, LibraryLogFileName = LibraryLogFileName, FlushTimeout = FlushTimeout }; _core = new AWSLoggerCore(config, "Log4net"); } /// <summary> /// Append method of AppenderSkeleton is called when a new message gets logged. /// </summary> /// <param name="loggingEvent"> /// LoggingEvent containing information about the log message. /// </param> protected override void Append(LoggingEvent loggingEvent) { if (_core == null) return; _core.AddMessage(RenderLoggingEvent(loggingEvent)); } /// <inheritdoc /> public override bool Flush(int millisecondsTimeout) { _core?.Flush(); return base.Flush(millisecondsTimeout); } } }
267
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("78312e9b-bc7c-4af8-9153-dd72bbf4fd36")]
12
aws-logging-dotnet
aws
C#
using Microsoft.Extensions.Configuration; using Serilog; using Serilog.Configuration; using Serilog.Events; using Serilog.Formatting; using System; namespace AWS.Logger.SeriLog { /// <summary> /// Extensions methods for <see cref="LoggerSinkConfiguration"/> to register <see cref="AWSSink"/> /// </summary> public static class AWSLoggerSeriLogExtension { internal const string LOG_GROUP = "Serilog:LogGroup"; internal const string DISABLE_LOG_GROUP_CREATION = "Serilog:DisableLogGroupCreation"; internal const string REGION = "Serilog:Region"; internal const string SERVICEURL = "Serilog:ServiceUrl"; internal const string PROFILE = "Serilog:Profile"; internal const string PROFILE_LOCATION = "Serilog:ProfilesLocation"; internal const string BATCH_PUSH_INTERVAL = "Serilog:BatchPushInterval"; internal const string BATCH_PUSH_SIZE_IN_BYTES = "Serilog:BatchPushSizeInBytes"; internal const string MAX_QUEUED_MESSAGES = "Serilog:MaxQueuedMessages"; internal const string LOG_STREAM_NAME_SUFFIX = "Serilog:LogStreamNameSuffix"; internal const string LOG_STREAM_NAME_PREFIX = "Serilog:LogStreamNamePrefix"; internal const string LIBRARY_LOG_FILE_NAME = "Serilog:LibraryLogFileName"; internal const string LIBRARY_LOG_ERRORS = "Serilog:LibraryLogErrors"; internal const string FLUSH_TIMEOUT = "Serilog:FlushTimeout"; /// <summary> /// AWSSeriLogger target that is called when the customer is using /// Serilog.Settings.Configuration to set the SeriLogger configuration /// using a Json input. /// </summary> public static LoggerConfiguration AWSSeriLog( this LoggerSinkConfiguration loggerConfiguration, IConfiguration configuration, IFormatProvider iFormatProvider = null, ITextFormatter textFormatter = null, LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose) { AWSLoggerConfig config = new AWSLoggerConfig(); config.LogGroup = configuration[LOG_GROUP]; if (configuration[DISABLE_LOG_GROUP_CREATION] != null) { config.DisableLogGroupCreation = bool.Parse(configuration[DISABLE_LOG_GROUP_CREATION]); } if (configuration[REGION] != null) { config.Region = configuration[REGION]; } if (configuration[SERVICEURL] != null) { config.ServiceUrl = configuration[SERVICEURL]; } if (configuration[PROFILE] != null) { config.Profile = configuration[PROFILE]; } if (configuration[PROFILE_LOCATION] != null) { config.ProfilesLocation = configuration[PROFILE_LOCATION]; } if (configuration[BATCH_PUSH_INTERVAL] != null) { config.BatchPushInterval = TimeSpan.FromMilliseconds(Int32.Parse(configuration[BATCH_PUSH_INTERVAL])); } if (configuration[BATCH_PUSH_SIZE_IN_BYTES] != null) { config.BatchSizeInBytes = Int32.Parse(configuration[BATCH_PUSH_SIZE_IN_BYTES]); } if (configuration[MAX_QUEUED_MESSAGES] != null) { config.MaxQueuedMessages = Int32.Parse(configuration[MAX_QUEUED_MESSAGES]); } if (configuration[LOG_STREAM_NAME_SUFFIX] != null) { config.LogStreamNameSuffix = configuration[LOG_STREAM_NAME_SUFFIX]; } if (configuration[LOG_STREAM_NAME_PREFIX] != null) { config.LogStreamNamePrefix = configuration[LOG_STREAM_NAME_PREFIX]; } if (configuration[LIBRARY_LOG_FILE_NAME] != null) { config.LibraryLogFileName = configuration[LIBRARY_LOG_FILE_NAME]; } if (configuration[LIBRARY_LOG_ERRORS] != null) { config.LibraryLogErrors = Boolean.Parse(configuration[LIBRARY_LOG_ERRORS]); } if (configuration[FLUSH_TIMEOUT] != null) { config.FlushTimeout = TimeSpan.FromMilliseconds(Int32.Parse(configuration[FLUSH_TIMEOUT])); } return AWSSeriLog(loggerConfiguration, config, iFormatProvider, textFormatter, restrictedToMinimumLevel); } /// <summary> /// AWSSeriLogger target that is called when the customer /// explicitly creates a configuration of type AWSLoggerConfig /// to set the SeriLogger configuration. /// </summary> public static LoggerConfiguration AWSSeriLog( this LoggerSinkConfiguration loggerConfiguration, AWSLoggerConfig configuration = null, IFormatProvider iFormatProvider = null, ITextFormatter textFormatter = null, LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose) { return loggerConfiguration.Sink(new AWSSink(configuration, iFormatProvider, textFormatter), restrictedToMinimumLevel); } } }
116
aws-logging-dotnet
aws
C#
using System; using System.IO; using AWS.Logger.Core; using Serilog; using Serilog.Core; using Serilog.Events; using Serilog.Formatting; namespace AWS.Logger.SeriLog { /// <summary> /// A Serilog sink that can be used with the Serilogger logging library to send messages to AWS. /// </summary> public class AWSSink: ILogEventSink, IDisposable { AWSLoggerCore _core = null; IFormatProvider _iformatDriver; ITextFormatter _textFormatter; /// <summary> /// Default constructor /// </summary> public AWSSink() { } /// <summary> /// Constructor called by AWSLoggerSeriLoggerExtension /// </summary> public AWSSink(AWSLoggerConfig loggerConfiguration, IFormatProvider iFormatProvider = null, ITextFormatter textFormatter = null) { _core = new AWSLoggerCore(loggerConfiguration, "SeriLogger"); _iformatDriver = iFormatProvider; _textFormatter = textFormatter; } /// <summary> /// Method called to pass the LogEvent to the AWSLogger Sink /// </summary> /// <param name="logEvent"></param> public void Emit(LogEvent logEvent) { var message = RenderLogEvent(logEvent); // If there is no custom formatter passed that would have taken care of logging the exception then append the // exception to the log if one exists. if (_textFormatter == null && logEvent.Exception != null) { message = string.Concat(message, Environment.NewLine, logEvent.Exception.ToString(), Environment.NewLine); } else { message = string.Concat(message, Environment.NewLine); } _core.AddMessage(message); } private string RenderLogEvent(LogEvent logEvent) { if (_iformatDriver == null && _textFormatter != null) { using (var writer = new StringWriter()) { _textFormatter.Format(logEvent, writer); writer.Flush(); return writer.ToString(); } } return logEvent.RenderMessage(_iformatDriver); } private bool disposedValue = false; // To detect redundant calls /// <summary> /// Disposable Pattern /// </summary> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { try { _core.Close(); } catch (Exception) { // .. and as ugly as THIS is, .Dispose() methods shall not throw exceptions } } disposedValue = true; } } /// <inheritdoc/> public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } } }
105
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("180041e5-49b9-4e81-b2ad-d67eb440325c")]
11
aws-logging-dotnet
aws
C#
using System; using NLog; using NLog.Targets; using NLog.Common; using NLog.Config; using AWS.Logger; using AWS.Logger.Core; using Amazon.Runtime; namespace NLog.AWS.Logger { /// <summary> /// An NLog target that can be used with the NLog logging library to send messages to AWS. /// </summary> [Target("AWSTarget")] public class AWSTarget : TargetWithLayout, IAWSLoggerConfig { AWSLoggerConfig _config = new AWSLoggerConfig(); AWSLoggerCore _core = null; /// <summary> /// Default Constructor /// </summary> public AWSTarget() { this.OptimizeBufferReuse = true; } /// <summary> /// Gets and sets the LogGroup property. This is the name of the CloudWatch Logs group where /// streams will be created and log messages written to. /// </summary> [RequiredParameter] public string LogGroup { get { return _config.LogGroup; } set { _config.LogGroup = value; } } /// <summary> /// Determines whether or not to create a new Log Group, if the one specified by <see cref="LogGroup"/> doesn't already exist /// <seealso cref="AWSLoggerConfig.DisableLogGroupCreation"/> /// </summary> public bool DisableLogGroupCreation { get { return _config.DisableLogGroupCreation; } set { _config.DisableLogGroupCreation = value; } } /// <summary> /// Gets and sets the Profile property. The profile is used to look up AWS credentials in the profile store. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> public string Profile { get { return _config.Profile; } set { _config.Profile = value; } } /// <summary> /// Gets and sets the ProfilesLocation property. If this is not set the default profile store is used by the AWS SDK for .NET /// to look up credentials. This is most commonly used when you are running an application of on-priemse under a service account. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> public string ProfilesLocation { get { return _config.ProfilesLocation; } set { _config.ProfilesLocation = value; } } /// <summary> /// Gets and sets the Credentials property. These are the AWS credentials used by the AWS SDK for .NET to make service calls. /// <para> /// For understanding how credentials are determine view the top level documentation for AWSLoggerConfig class. /// </para> /// </summary> public AWSCredentials Credentials { get { return _config.Credentials; } set { _config.Credentials = value; } } /// <summary> /// Gets and sets the Region property. This is the AWS Region that will be used for CloudWatch Logs. If this is not /// the AWS SDK for .NET will use its fall back logic to try and determine the region through environment variables and EC2 instance metadata. /// If the Region is not set and no region is found by the SDK's fall back logic then an exception will be thrown. /// </summary> public string Region { get { return _config.Region; } set { _config.Region = value; } } /// <summary> /// Gets and sets of the ServiceURL property. This is an optional property; change /// it only if you want to try a different service endpoint. Ex. for LocalStack /// </summary> public string ServiceUrl { get { return _config.ServiceUrl; } set { _config.ServiceUrl = value; } } /// <summary> /// Gets and sets the BatchPushInterval property. For performance the log messages are sent to AWS in batch sizes. BatchPushInterval /// dictates the frequency of when batches are sent. If either BatchPushInterval or BatchSizeInBytes are exceeded the batch will be sent. /// <para> /// The default is 3 seconds. /// </para> /// </summary> public TimeSpan BatchPushInterval { get { return _config.BatchPushInterval; } set { _config.BatchPushInterval = value; } } /// <summary> /// Gets and sets the BatchSizeInBytes property. For performance the log messages are sent to AWS in batch sizes. BatchSizeInBytes /// dictates the total size of the batch in bytes when batches are sent. If either BatchPushInterval or BatchSizeInBytes are exceeded the batch will be sent. /// <para> /// The default is 100 Kilobytes. /// </para> /// </summary> public int BatchSizeInBytes { get { return _config.BatchSizeInBytes; } set { _config.BatchSizeInBytes = value; } } /// <summary> /// Gets and sets the MaxQueuedMessages property. This specifies the maximum number of log messages that could be stored in-memory. MaxQueuedMessages /// dictates the total number of log messages that can be stored in-memory. If this is exceeded, incoming log messages will be dropped. /// <para> /// The default is 10000. /// </para> /// </summary> public int MaxQueuedMessages { get { return _config.MaxQueuedMessages; } set { _config.MaxQueuedMessages = value; } } /// <summary> /// Gets and sets the LogStreamNameSuffix property. The LogStreamName consists of an optional user-defined prefix segment, then a DateTimeStamp as the /// system-defined prefix segment, and a user defined suffix value that can be set using the LogStreamNameSuffix property defined here. /// <para> /// The default is going to a Guid. /// </para> /// </summary> public string LogStreamNameSuffix { get { return _config.LogStreamNameSuffix; } set { _config.LogStreamNameSuffix = value; } } /// <summary> /// Gets and sets the LogStreamNamePrefix property. The LogStreamName consists of an optional user-defined prefix segment (defined here), then a /// DateTimeStamp as the system-defined prefix segment, and a user defined suffix value that can be set using the LogStreamNameSuffix property. /// <para> /// The default will use an empty string for this user-defined portion, meaning the log stream name will start with the system-defined portion of the prefix (yyyy/MM/dd ... ) /// </para> /// </summary> public string LogStreamNamePrefix { get { return _config.LogStreamNamePrefix; } set { _config.LogStreamNamePrefix = value; } } /// <summary> /// Gets and sets the LibraryLogErrors property. This is the boolean value of whether or not you would like this library to log logging errors. /// <para> /// The default is "true". /// </para> /// </summary> public bool LibraryLogErrors { get { return _config.LibraryLogErrors; } set { _config.LibraryLogErrors = value; } } /// <summary> /// Gets and sets the LibraryLogFileName property. This is the name of the file into which errors from the AWS.Logger.Core library will be written into. /// <para> /// The default is "aws-logger-errors.txt". /// </para> /// </summary> public string LibraryLogFileName { get { return _config.LibraryLogFileName; } set { _config.LibraryLogFileName = value; } } /// <summary> /// Gets the FlushTimeout property. The value is in milliseconds. When performing a flush of the in-memory queue this is the maximum period of time allowed to send the remaining /// messages before it will be aborted. If this is exceeded, incoming log messages will be dropped. /// <para> /// The default is 30000 milliseconds. /// </para> /// </summary> public TimeSpan FlushTimeout { get { return _config.FlushTimeout; } set { _config.FlushTimeout = value; } } /// <inheritdoc/> protected override void InitializeTarget() { if (_core != null) { _core.Close(); _core = null; } var config = new AWSLoggerConfig(RenderSimpleLayout(LogGroup, nameof(LogGroup))) { DisableLogGroupCreation = DisableLogGroupCreation, Region = RenderSimpleLayout(Region, nameof(Region)), ServiceUrl = RenderSimpleLayout(ServiceUrl, nameof(ServiceUrl)), Credentials = Credentials, Profile = RenderSimpleLayout(Profile, nameof(Profile)), ProfilesLocation = RenderSimpleLayout(ProfilesLocation, nameof(ProfilesLocation)), BatchPushInterval = BatchPushInterval, BatchSizeInBytes = BatchSizeInBytes, MaxQueuedMessages = MaxQueuedMessages, LogStreamNameSuffix = RenderSimpleLayout(LogStreamNameSuffix, nameof(LogStreamNameSuffix)), LogStreamNamePrefix = RenderSimpleLayout(LogStreamNamePrefix, nameof(LogStreamNamePrefix)), LibraryLogErrors = LibraryLogErrors, LibraryLogFileName = LibraryLogFileName, FlushTimeout = FlushTimeout }; _core = new AWSLoggerCore(config, "NLog"); _core.LogLibraryAlert += AwsLogLibraryAlert; } private string RenderSimpleLayout(string simpleLayout, string propertyName) { try { return string.IsNullOrEmpty(simpleLayout) ? string.Empty : new Layouts.SimpleLayout(simpleLayout).Render(LogEventInfo.CreateNullEvent()); } catch (Exception ex) { InternalLogger.Debug(ex, "AWSTarget(Name={0}) - Could not render Layout for {1}", Name, propertyName); return simpleLayout; } } private void AwsLogLibraryAlert(object sender, AWSLoggerCore.LogLibraryEventArgs e) { InternalLogger.Error(e.Exception, "AWSTarget(Name={0}) - CloudWatch Network Error - ServiceUrl={1}", Name, e.ServiceUrl); } /// <inheritdoc/> protected override void Write(LogEventInfo logEvent) { var message = RenderLogEvent(this.Layout, logEvent); _core.AddMessage(message); } /// <inheritdoc/> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { _core.Flush(); asyncContinuation(null); } catch (Exception ex) { asyncContinuation(ex); } } } }
286
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("284abc3b-da69-4038-a025-0212a6df65a3")]
10
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AWS.Logger.Core; using System.Collections.Concurrent; namespace AWS.Logger.AspNetCore.Tests { /// <summary> /// FakeCoreLogger class used to make mock test calls instead of the actual AWS CloudWatchLogs. /// Implements the IAWSLoggerCore interface of AWS Logger Core /// </summary> public class FakeCoreLogger : IAWSLoggerCore { public ConcurrentQueue<string> ReceivedMessages { get; private set; } = new ConcurrentQueue<string>(); public void AddMessage(string message) { ReceivedMessages.Enqueue(message); } public void Flush() { } public void Close() { } public void StartMonitor() { } } }
38
aws-logging-dotnet
aws
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using Xunit; using AWS.Logger.AspNetCore; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using AWS.Logger.TestUtils; namespace AWS.Logger.AspNetCore.Tests { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. // In the Build tab select "Produce outputs on build". public class ILoggerTestClass : BaseTestClass { #region Properties public ILogger Logger; public AWSLoggerConfigSection ConfigSection; public IServiceCollection ServiceCollection; public IServiceProvider Provider; #endregion public ILoggerTestClass(TestFixture testFixture) : base(testFixture) { ServiceCollection = new ServiceCollection(); } /// <summary> /// Setup class that marks down the _configSection, upon which the logger object would be created /// and instantiates the ILogger object. /// </summary> /// <param name="configFileName">The configuration file that contains the user's config data as a Json file.</param> /// <param name="configSectionInfoBlockName">The Json object name that contains the AWS Logging configuration information /// . The Default value is "AWS.Logging".</param> /// <param name="sourceFilePath">The source file path specifies the path for the configuration file.</param> private void LoggingSetup(string configFileName, string configSectionInfoBlockName, [System.Runtime.CompilerServices.CallerFilePath]string sourceFilePath = "") { var configurationBuilder = new ConfigurationBuilder() .SetBasePath(Path.GetDirectoryName(sourceFilePath)) .AddJsonFile(configFileName); if (configSectionInfoBlockName != null) { ConfigSection = configurationBuilder .Build() .GetAWSLoggingConfigSection(configSectionInfoBlockName); } else { ConfigSection = configurationBuilder .Build() .GetAWSLoggingConfigSection(); } var loggingFactoryService = this.ServiceCollection.FirstOrDefault(x => x.ServiceType is ILoggerFactory); this.Provider = this.ServiceCollection.AddLogging(logging => logging.SetMinimumLevel(LogLevel.Debug)) .BuildServiceProvider(); if (loggingFactoryService == null) { var loggingFactory = this.Provider.GetService<ILoggerFactory>(); loggingFactory.AddAWSProvider(ConfigSection); Logger = loggingFactory.CreateLogger<ILoggerTestClass>(); } } #region Tests /// <summary> /// Basic test case that reads the configuration from "appsettings.json", creates a log object and logs /// 10 debug messages to CloudWatchLogs. The results are then verified. /// </summary> [Fact] public void ILogger() { LoggingSetup("appsettings.json",null); SimpleLoggingTest(ConfigSection.Config.LogGroup); } [Fact] public void ExceptionMockTest() { var categoryName = "testlogging"; var coreLogger = new FakeCoreLogger(); Logger = new AWSLogger( categoryName, coreLogger, null); var logMessageCount = 10; LogMessages(logMessageCount); Assert.Contains($"[Error] testlogging: Error message System.Exception: Exception message.{Environment.NewLine}", coreLogger.ReceivedMessages); } /// <summary> /// Basic test case that creates multiple threads and each thread mocks log messages /// onto the FakeCoreLogger. The results are then verified. /// </summary> [Fact] public void MultiThreadTestMock() { var categoryName = "testlogging"; var coreLogger = new FakeCoreLogger(); Logger = new AWSLogger( categoryName, coreLogger, null); var tasks = new List<Task>(); var logMessageCount = 200; var actualCount = 0; for (int i = 0; i < 2; i++) { tasks.Add(Task.Factory.StartNew(() => LogMessages(logMessageCount))); actualCount = actualCount + logMessageCount; } Task.WaitAll(tasks.ToArray()); Assert.Equal(actualCount, coreLogger.ReceivedMessages.Count); } /// <summary> /// Basic test case that reads the configuration from "appsettings.json", /// creates a log object and spools multiple /// threads that log 200 debug messages each to CloudWatchLogs. The results are then verified. /// </summary> [Fact] public void MultiThreadTest() { LoggingSetup("multiThreadTest.json",null); MultiThreadTestGroup(ConfigSection.Config.LogGroup); } /// <summary> /// Basic test case that reads the configuration from "multiThreadBufferFullTest.json", /// creates a log object and spools multiple /// threads that log 200 debug messages each to CloudWatchLogs with a reduced buffer /// size of just 10 messages /// inorder to force a buffer full scenario. The results are then verified. /// </summary> [Fact] public void MultiThreadBufferFullTest() { LoggingSetup("multiThreadBufferFullTest.json",null); MultiThreadBufferFullTestGroup(ConfigSection.Config.LogGroup); } /// <summary> /// This method posts debug messages onto CloudWatchLogs. /// </summary> /// <param name="count">The number of messages that would be posted onto CloudWatchLogs</param> protected override void LogMessages(int count) { Logger.LogError(0, new Exception("Exception message."), "Error message"); for (int i = 0; i < count-2; i++) { Logger.LogDebug(string.Format("Test logging message {0} Ilogger, Thread Id:{1}", i, Thread.CurrentThread.ManagedThreadId)); } Logger.LogDebug(LASTMESSAGE); } #endregion } }
167
aws-logging-dotnet
aws
C#
using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace AWS.Logger.AspNetCore.Tests { /// <summary> /// provides access to methods helpful when dealing with configuration in .net core JSON form /// </summary> public class TestConfigurationBase { /// <summary> /// read IConfiguration from a JSON file, for testing purposes /// </summary> /// <param name="jsonFileName"></param> /// <param name="configSectionInfoBlockName"></param> /// <param name="sourceFilePath"></param> /// <returns>IConfiguration from a JSON file</returns> public IConfiguration LoggerConfigSectionSetup(string jsonFileName, string configSectionInfoBlockName, [System.Runtime.CompilerServices.CallerFilePath]string sourceFilePath = "") { var configurationBuilder = new ConfigurationBuilder() .SetBasePath(Path.GetDirectoryName(sourceFilePath)) .AddJsonFile(jsonFileName); IConfiguration Config; if (configSectionInfoBlockName != null) { Config = configurationBuilder .Build() .GetSection(configSectionInfoBlockName); } else { Config = configurationBuilder .Build() .GetSection("AWS.Logging"); } return Config; } } }
47
aws-logging-dotnet
aws
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using Xunit; using AWS.Logger.AspNetCore; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using AWS.Logger.TestUtils; namespace AWS.Logger.AspNetCore.Tests { public class TestDisableLogGroupCreation : TestConfigurationBase { [Fact] public void TestMissingDisableLogGroupCreation() { var config = LoggerConfigSectionSetup("disableLogGroupCreationMissing.json", null); var typed = new AWSLoggerConfigSection(config); Assert.False(typed.Config.DisableLogGroupCreation); } [Fact] public void TestTrueDisableLogGroupCreation() { var config = LoggerConfigSectionSetup("disableLogGroupCreationTrue.json", null); var typed = new AWSLoggerConfigSection(config); Assert.True(typed.Config.DisableLogGroupCreation); } } }
37
aws-logging-dotnet
aws
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Hosting; using Xunit; using System; using Microsoft.Extensions.DependencyInjection; using System.IO; using System.Reflection; using System.Linq; namespace AWS.Logger.AspNetCore.Tests { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". public class TestFilter : TestConfigurationBase { public AWSLoggerConfigSection ConfigSection; [Fact] public void FilterLogLevel() { var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger("FilterLogLevel", coreLogger, AWSLoggerProvider.CreateLogLevelFilter(LogLevel.Warning)); logger.LogTrace("trace"); logger.LogDebug("debug"); logger.LogInformation("information"); logger.LogWarning("warning"); logger.LogError("error"); logger.LogCritical("critical"); Assert.Equal(3, coreLogger.ReceivedMessages.Count); Assert.Contains($"[Warning] FilterLogLevel: warning{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Error] FilterLogLevel: error{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Critical] FilterLogLevel: critical{Environment.NewLine}", coreLogger.ReceivedMessages); } [Fact] public void CustomFilter() { var coreLogger = new FakeCoreLogger(); Func<string, LogLevel, bool> filter = (categoryName, level) => { if (string.Equals(categoryName, "goodCategory", StringComparison.OrdinalIgnoreCase) && level >= LogLevel.Warning) return true; return false; }; var logger = new AWSLogger("goodCategory", coreLogger, filter); logger.LogTrace("trace"); logger.LogWarning("warning"); Assert.Single(coreLogger.ReceivedMessages); Assert.Contains($"[Warning] goodCategory: warning{Environment.NewLine}", coreLogger.ReceivedMessages); string val; while (!coreLogger.ReceivedMessages.IsEmpty) { coreLogger.ReceivedMessages.TryDequeue(out val); } logger = new AWSLogger("badCategory", coreLogger, filter); logger.LogTrace("trace"); logger.LogWarning("warning"); Assert.Empty(coreLogger.ReceivedMessages); } [Fact] public void ValidAppsettingsFilter() { var configSection = LoggerConfigSectionSetup("ValidAppsettingsFilter.json",null).GetSection("LogLevel"); if (!(configSection != null && configSection.GetChildren().Count() > 0)) { configSection = null; } var categoryName = typeof(TestFilter).GetTypeInfo().FullName; var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger( categoryName, coreLogger, AWSLoggerProvider.CreateConfigSectionFilter(configSection, categoryName)); logger.LogTrace("trace"); logger.LogDebug("debug"); logger.LogInformation("information"); logger.LogWarning("warning"); logger.LogError("error"); logger.LogCritical("critical"); Assert.Equal(5, coreLogger.ReceivedMessages.Count); Assert.Contains($"[Warning] AWS.Logger.AspNetCore.Tests.TestFilter: warning{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Error] AWS.Logger.AspNetCore.Tests.TestFilter: error{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Critical] AWS.Logger.AspNetCore.Tests.TestFilter: critical{Environment.NewLine}", coreLogger.ReceivedMessages); } [Fact] public void InValidAppsettingsFilter() { var configSection = LoggerConfigSectionSetup("InValidAppsettingsFilter.json",null).GetSection("LogLevel"); if (!(configSection != null && configSection.GetChildren().Count() > 0)) { configSection = null; } var categoryName = typeof(TestFilter).GetTypeInfo().FullName; var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger( categoryName, coreLogger, AWSLoggerProvider.CreateConfigSectionFilter(configSection, categoryName)); logger.LogTrace("trace"); logger.LogDebug("debug"); logger.LogInformation("information"); logger.LogWarning("warning"); logger.LogError("error"); logger.LogCritical("critical"); Assert.Empty(coreLogger.ReceivedMessages); categoryName = "AWS.Log"; logger = new AWSLogger( categoryName, coreLogger, AWSLoggerProvider.CreateConfigSectionFilter(configSection, categoryName)); logger.LogTrace("trace"); logger.LogDebug("debug"); logger.LogInformation("information"); logger.LogWarning("warning"); logger.LogError("error"); logger.LogCritical("critical"); Assert.Equal(5, coreLogger.ReceivedMessages.Count); Assert.Contains($"[Warning] AWS.Log: warning{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Error] AWS.Log: error{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Critical] AWS.Log: critical{Environment.NewLine}", coreLogger.ReceivedMessages); } [Fact] public void DefaultFilterCheck() { var configSection = LoggerConfigSectionSetup("DefaultFilterCheck.json", null).GetSection("LogLevel"); if (!(configSection != null && configSection.GetChildren().Count() > 0)) { configSection = null; } var categoryName = "AWS.Log"; var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger( categoryName, coreLogger, AWSLoggerProvider.CreateConfigSectionFilter(configSection, categoryName)); logger.LogTrace("trace"); logger.LogDebug("debug"); logger.LogInformation("information"); logger.LogWarning("warning"); logger.LogError("error"); logger.LogCritical("critical"); Assert.Equal(5, coreLogger.ReceivedMessages.Count); Assert.Contains($"[Warning] AWS.Log: warning{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Error] AWS.Log: error{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Critical] AWS.Log: critical{Environment.NewLine}", coreLogger.ReceivedMessages); } [Fact] public void MissingLogLevelCheck() { var configSection = LoggerConfigSectionSetup("MissingLogLevelCheck.json", null).GetSection("LogLevel"); if (!(configSection != null && configSection.GetChildren().Count() > 0)) { configSection = null; } var categoryName = typeof(TestFilter).GetTypeInfo().FullName; var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger( categoryName, coreLogger, AWSLoggerProvider.CreateConfigSectionFilter(configSection, categoryName)); logger.LogTrace("trace"); logger.LogDebug("debug"); logger.LogInformation("information"); logger.LogWarning("warning"); logger.LogError("error"); logger.LogCritical("critical"); Assert.Equal(6, coreLogger.ReceivedMessages.Count); Assert.Contains($"[Warning] AWS.Logger.AspNetCore.Tests.TestFilter: warning{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Error] AWS.Logger.AspNetCore.Tests.TestFilter: error{Environment.NewLine}", coreLogger.ReceivedMessages); Assert.Contains($"[Critical] AWS.Logger.AspNetCore.Tests.TestFilter: critical{Environment.NewLine}", coreLogger.ReceivedMessages); } } }
198
aws-logging-dotnet
aws
C#
using Microsoft.Extensions.Logging; using System; using System.Linq; using Xunit; namespace AWS.Logger.AspNetCore.Tests { public class TestFormatter { [Theory] [InlineData("my log message", LogLevel.Trace)] [InlineData("my log message", LogLevel.Debug)] [InlineData("my log message", LogLevel.Critical)] public void CustomFormatter_Must_Be_Applied(string message, LogLevel logLevel) { Func<LogLevel, object, Exception, string> customFormatter = (level, state, ex) => level + " hello world" + state.ToString(); Func<string, LogLevel, bool> filter = (categoryName, level) => true; var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger("TestCategory", coreLogger, filter, customFormatter); logger.Log(logLevel, 0, message, null, (state, ex) => state.ToString()); string expectedMessage = customFormatter(logLevel, message, null); Assert.Equal(expectedMessage, coreLogger.ReceivedMessages.First().Replace(Environment.NewLine, string.Empty)); } } }
33
aws-logging-dotnet
aws
C#
using System; using System.Linq; using Microsoft.Extensions.Logging; using Xunit; namespace AWS.Logger.AspNetCore.Tests { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". public class TestScope { [Fact] // Make sure that a message will be logged inside a scope, even when scopes are not included. public void MakeSureCanCreateScope() { var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger("MakeSureCanCreateScope", coreLogger, null) { IncludeScopes = false }; using (logger.BeginScope("Test Scope")) { logger.LogInformation("log"); } Assert.Single(coreLogger.ReceivedMessages); Assert.True(coreLogger.ReceivedMessages.Contains($"[Information] MakeSureCanCreateScope: log{Environment.NewLine}"), "Messages don't contain actual log message."); } [Fact] // Make sure that a message will be logged outside a scope, even when scopes are included. public void MakeSureCanLogWithoutScope() { var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger("MakeSureCanCreateScope", coreLogger, null) { IncludeScopes = true }; logger.LogInformation("log"); Assert.Single(coreLogger.ReceivedMessages); var msg = coreLogger.ReceivedMessages.SingleOrDefault(m => m.Contains($"[Information] MakeSureCanCreateScope: log{Environment.NewLine}")); Assert.True(msg != null, "Messages don't contain actual log message."); Assert.False(msg.Contains("=>"), "Fragment of scopes exists (\"=>\")."); } [Fact] // Make sure that a message inside a scope will be logged together with the scope. public void MakeSureScopeIsIncluded() { var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger("MakeSureCanCreateScope", coreLogger, null) { IncludeScopes = true }; using (logger.BeginScope("Test scope")) { logger.LogInformation("log"); } Assert.Single(coreLogger.ReceivedMessages); var msg = coreLogger.ReceivedMessages.SingleOrDefault(m => m.Contains($"[Information] Test scope => MakeSureCanCreateScope: log{Environment.NewLine}")); Assert.True(msg != null, "Messages don't contain actual log message."); // Same message should contain the scope Assert.True(msg.Contains("Test scope => "), "Scope is not included."); } [Fact] // Make sure that a message inside multiple scopes will be logged together with the scopes. public void MakeSureScopesAreIncluded() { var coreLogger = new FakeCoreLogger(); var logger = new AWSLogger("MakeSureCanCreateScope", coreLogger, null) { IncludeScopes = true }; using (logger.BeginScope("OuterScope")) { using (logger.BeginScope("InnerScope")) { logger.LogInformation("log"); } } Assert.Single(coreLogger.ReceivedMessages); var msg = coreLogger.ReceivedMessages.SingleOrDefault(m => m.Contains($"[Information] OuterScope InnerScope => MakeSureCanCreateScope: log{Environment.NewLine}")); Assert.True(msg != null, "Messages don't contain actual log message."); // Same message should contain the scope Assert.True(msg.Contains("OuterScope"), "Outer scope is not included."); Assert.True(msg.Contains("InnerScope"), "Inner scope is not included."); } } }
98
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AWS.Logger.AspNetCore.Tests")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("77b72c22-7b5c-4412-98bf-9714574d8ad6")]
19
aws-logging-dotnet
aws
C#
using System; using log4net.Appender; using log4net.Core; namespace AWS.Logger.Log4Net.FilterTests { /// <summary> /// A mock Log4net appender that sends logging messages to a mock AWS Logger Core. /// </summary> public class FakeAWSAppender : AppenderSkeleton { public FakeCoreLogger _core = new FakeCoreLogger(); protected override void Append(LoggingEvent loggingEvent) { if (_core == null) return; _core.AddMessage(RenderLoggingEvent(loggingEvent)); } } }
25
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AWS.Logger.Core; using System.Collections.Concurrent; namespace AWS.Logger.Log4Net.FilterTests { public class FakeCoreLogger : IAWSLoggerCore { public ConcurrentQueue<string> ReceivedMessages { get; private set; } = new ConcurrentQueue<string>(); public void AddMessage(string message) { ReceivedMessages.Enqueue(message); } public void Flush() { } public void Close() { } public void StartMonitor() { } } }
33
aws-logging-dotnet
aws
C#
using Xunit; using System; using System.IO; using System.Reflection; using System.Linq; using log4net.Repository.Hierarchy; using log4net; using log4net.Layout; using log4net.Core; namespace AWS.Logger.Log4Net.FilterTests { public class TestFilter { static Assembly repositoryAssembly = typeof(TestFilter).GetTypeInfo().Assembly; [Fact] public void FilterLogLevel() { FakeAWSAppender awsAppender; ILog logger; Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(repositoryAssembly); PatternLayout patternLayout = new PatternLayout(); patternLayout.ConversionPattern = "%-4timestamp [%thread] %-5level %logger %ndc - %message%newline"; patternLayout.ActivateOptions(); awsAppender = new FakeAWSAppender(); awsAppender.Layout = patternLayout; var filter = new log4net.Filter.LevelRangeFilter(); filter.LevelMax = Level.Fatal; filter.LevelMin = Level.Warn; awsAppender.AddFilter(filter); awsAppender.ActivateOptions(); hierarchy.Root.AddAppender(awsAppender); hierarchy.Root.Level = Level.All; hierarchy.Configured = true; logger = LogManager.GetLogger(repositoryAssembly, "FilterLogLevel"); logger.Debug("debug"); logger.Info("information"); logger.Warn("warning"); logger.Error("error"); logger.Fatal("fatal"); Assert.Equal(3, awsAppender._core.ReceivedMessages.Count); Assert.Contains("warning", awsAppender._core.ReceivedMessages.ElementAt(0)); Assert.Contains("error", awsAppender._core.ReceivedMessages.ElementAt(1)); Assert.Contains("fatal", awsAppender._core.ReceivedMessages.ElementAt(2)); } [Fact] public void CustomFilter() { FakeAWSAppender awsAppender; ILog logger; Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(repositoryAssembly); PatternLayout patternLayout = new PatternLayout(); patternLayout.ConversionPattern = "%logger %ndc - %message%newline"; patternLayout.ActivateOptions(); awsAppender = new FakeAWSAppender(); awsAppender.Layout = patternLayout; var filterName = new log4net.Filter.LoggerMatchFilter(); filterName.LoggerToMatch = "badCategory"; filterName.AcceptOnMatch = false; awsAppender.AddFilter(filterName); awsAppender.ActivateOptions(); hierarchy.Root.AddAppender(awsAppender); hierarchy.Root.Level = Level.All; hierarchy.Configured = true; logger = LogManager.GetLogger(repositoryAssembly,"goodCategory"); logger.Debug("trace"); logger.Warn("warning"); Assert.Equal(2, awsAppender._core.ReceivedMessages.Count); Assert.Contains("warning", awsAppender._core.ReceivedMessages.ElementAt(1)); string val; while (!awsAppender._core.ReceivedMessages.IsEmpty) { awsAppender._core.ReceivedMessages.TryDequeue(out val); } logger = LogManager.GetLogger(repositoryAssembly,"badCategory"); logger.Debug("trace"); logger.Warn("warning"); Assert.Empty(awsAppender._core.ReceivedMessages); } } }
105
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AWS.Logger.Log4Net.FilterTests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1a4e2bc7-cfe5-4532-9cfd-4dc1efa0ad82")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")]
32
aws-logging-dotnet
aws
C#
using System; using System.Reflection; using System.Threading; using AWS.Logger.TestUtils; using log4net; using log4net.Config; using Xunit; namespace AWS.Logger.Log4Net.Tests { public class Log4NetTestClass : BaseTestClass { public ILog Logger; private void GetLog4NetLogger(string fileName, string logName) { // Create logger var repositoryAssembly = typeof(Log4NetTestClass).GetTypeInfo().Assembly; var loggerRepository = LogManager.GetRepository(repositoryAssembly); XmlConfigurator.Configure(loggerRepository, new System.IO.FileInfo(fileName)); Logger = LogManager.GetLogger(repositoryAssembly, logName); } public Log4NetTestClass(TestFixture testFixture) : base(testFixture) { } #region Test Cases [Fact] public void Log4Net() { GetLog4NetLogger("log4net.config","Log4Net"); SimpleLoggingTest("AWSLog4NetGroupLog4Net"); } [Fact] public void MultiThreadTest() { GetLog4NetLogger("MultiThreadTest.config", "MultiThreadTest"); MultiThreadTestGroup("AWSLog4NetGroupLog4NetMultiThreadTest"); } [Fact] public void MultiThreadBufferFullTest() { GetLog4NetLogger("MultiThreadBufferFullTest.config", "MultiThreadBufferFullTest"); MultiThreadBufferFullTestGroup("AWSLog4NetGroupMultiThreadBufferFullTest"); } protected override void LogMessages(int count) { for (int i = 0; i < count-1; i++) { Logger.Debug(string.Format("Test logging message {0} Log4Net, Thread Id:{1}", i, Thread.CurrentThread.ManagedThreadId)); } Logger.Debug(LASTMESSAGE); } #endregion } }
61
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AWS.Logger.Log4Net.Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("91cf836a-4d1c-489f-9475-6c7c2673d617")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")]
32
aws-logging-dotnet
aws
C#
using System; using NLog; using NLog.Common; using NLog.Targets; namespace AWS.Logger.NLogger.FilterTests { [Target("FakeAWSTarget")] public class FakeAWSTarget : TargetWithLayout { public FakeCoreLogger _core; public FakeAWSTarget(TimeSpan asyncDelay = default(TimeSpan)) { _core = new FakeCoreLogger(asyncDelay); } protected override void Write(LogEventInfo logEvent) { var message = this.Layout.Render(logEvent); _core.AddMessage(message); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { _core.Flush(); asyncContinuation(null); } catch (Exception ex) { asyncContinuation(ex); } } } }
38
aws-logging-dotnet
aws
C#
using System; using System.Threading; using System.Threading.Tasks; using AWS.Logger.Core; using System.Collections.Concurrent; namespace AWS.Logger.NLogger.FilterTests { public class FakeCoreLogger : IAWSLoggerCore { ConcurrentQueue<string> _pendingMessages = new ConcurrentQueue<string>(); public ConcurrentQueue<string> ReceivedMessages { get; private set; } = new ConcurrentQueue<string>(); private SemaphoreSlim _flushTriggerEvent; private ManualResetEventSlim _flushCompletedEvent; private CancellationTokenSource _closeTokenSource; TimeSpan _asyncDelay; public FakeCoreLogger(TimeSpan asyncDelay = default(TimeSpan)) { _asyncDelay = asyncDelay; } public void AddMessage(string message) { if (_asyncDelay == TimeSpan.Zero) { ReceivedMessages.Enqueue(message); } else { if (_flushTriggerEvent == null) { _flushTriggerEvent = new SemaphoreSlim(0, 1); _flushCompletedEvent = new ManualResetEventSlim(false); _closeTokenSource = new CancellationTokenSource(); Task.Run(async () => { await Task.Delay(100).ConfigureAwait(false); // Simulate slow connection bool flushNow = false; do { while (_pendingMessages.TryDequeue(out var msg)) { await Task.Delay(50); ReceivedMessages.Enqueue(msg); } if (flushNow) _flushCompletedEvent.Set(); flushNow = await _flushTriggerEvent.WaitAsync(_asyncDelay); } while (!_closeTokenSource.IsCancellationRequested); }, _closeTokenSource.Token); } _pendingMessages.Enqueue(message); } } public void Flush() { if (_flushTriggerEvent != null) { bool lockTaken = false; try { // Ensure only one thread executes the flush operation System.Threading.Monitor.TryEnter(_flushTriggerEvent, ref lockTaken); if (lockTaken) { _flushCompletedEvent.Reset(); _flushTriggerEvent.Release(); // Signal Monitor-Task to start premature flush } _flushCompletedEvent.Wait(TimeSpan.FromSeconds(15)); } finally { if (lockTaken) System.Threading.Monitor.Exit(_flushTriggerEvent); } } } public void Close() { Flush(); _closeTokenSource.Cancel(); } public void StartMonitor() { } } }
95
aws-logging-dotnet
aws
C#
using Xunit; using System; using System.IO; using System.Reflection; using System.Linq; using NLog.Config; using NLog; using NLog.Filters; namespace AWS.Logger.NLogger.FilterTests { public class TestFilter { [Fact] public void FilterLogLevel() { var config = new LoggingConfiguration(); FakeAWSTarget proxyawsTarget = new FakeAWSTarget(); config.AddTarget("FakeAWSTarget", proxyawsTarget); config.AddRule(LogLevel.Warn, LogLevel.Fatal, proxyawsTarget, "FilterLogLevel"); LogManager.Configuration = config; var logger = LogManager.GetLogger("FilterLogLevel"); logger.Trace("trace"); logger.Debug("debug"); logger.Info("information"); logger.Warn("warning"); logger.Error("error"); logger.Fatal("fatal"); Assert.Equal(3, proxyawsTarget._core.ReceivedMessages.Count); Assert.Contains("warning", proxyawsTarget._core.ReceivedMessages.ElementAt(0)); Assert.Contains("error", proxyawsTarget._core.ReceivedMessages.ElementAt(1)); Assert.Contains("fatal", proxyawsTarget._core.ReceivedMessages.ElementAt(2)); } [Fact] public void CustomFilter() { var filter = new ConditionBasedFilter(); filter.Condition = "starts-with('${message}','badCategory')"; filter.Action = FilterResult.Ignore; FakeAWSTarget fakeawsTarget = new FakeAWSTarget(); var config = new LoggingConfiguration(); config.AddTarget("FakeAWSTarget", fakeawsTarget); var rule = new LoggingRule("CustomFilter", LogLevel.Warn,LogLevel.Fatal, fakeawsTarget); rule.Filters.Add(filter); config.LoggingRules.Add(rule); LogManager.Configuration = config; var logger = LogManager.GetLogger("CustomFilter"); logger.Trace("goodCategory|trace"); logger.Fatal("goodCategory|fatal"); Assert.Single(fakeawsTarget._core.ReceivedMessages); Assert.Contains("fatal", fakeawsTarget._core.ReceivedMessages.ElementAt(0)); string val; while (!fakeawsTarget._core.ReceivedMessages.IsEmpty) { fakeawsTarget._core.ReceivedMessages.TryDequeue(out val); } logger.Trace("badCategory|trace"); logger.Warn("badCategory|warning"); Assert.Empty(fakeawsTarget._core.ReceivedMessages); } [Fact] public void AsyncFlushLogLevel() { var config = new LoggingConfiguration(); FakeAWSTarget proxyawsTarget = new FakeAWSTarget(TimeSpan.FromSeconds(10)); config.AddTarget("FakeAWSTarget", proxyawsTarget); config.AddRule(LogLevel.Warn, LogLevel.Fatal, proxyawsTarget, "FilterLogLevel"); LogManager.Configuration = config; var logger = LogManager.GetLogger("FilterLogLevel"); logger.Trace("trace"); logger.Debug("debug"); logger.Info("information"); logger.Warn("warning"); Assert.Empty(proxyawsTarget._core.ReceivedMessages); LogManager.Flush(); Assert.Single(proxyawsTarget._core.ReceivedMessages); logger.Error("error"); logger.Fatal("fatal"); LogManager.Flush(); Assert.Equal(3, proxyawsTarget._core.ReceivedMessages.Count); Assert.Contains("warning", proxyawsTarget._core.ReceivedMessages.ElementAt(0)); Assert.Contains("error", proxyawsTarget._core.ReceivedMessages.ElementAt(1)); Assert.Contains("fatal", proxyawsTarget._core.ReceivedMessages.ElementAt(2)); } } }
107
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AWS.Logger.NLog.FilterTests")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("48377844-b524-46ac-b465-246a1552fe64")]
19
aws-logging-dotnet
aws
C#
using System; using System.Threading; using Amazon.CloudWatchLogs.Model; using AWS.Logger.TestUtils; using NLog; using NLog.Config; using Xunit; namespace AWS.Logger.NLogger.Tests { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". public class NLogTestClass: BaseTestClass { public NLog.Logger Logger; private void CreateLoggerFromConfiguration(string configFileName) { LogManager.Configuration = new XmlLoggingConfiguration(configFileName); } public NLogTestClass(TestFixture testFixture) : base(testFixture) { } #region Test Cases [Fact] public void Nlog() { CreateLoggerFromConfiguration("Regular.config"); Logger = LogManager.GetLogger("loggerRegular"); SimpleLoggingTest("AWSNLogGroup"); } [Fact] public void MultiThreadTest() { CreateLoggerFromConfiguration("AWSNLogGroupMultiThreadTest.config"); Logger = LogManager.GetLogger("loggerMultiThread"); MultiThreadTestGroup("AWSNLogGroupMultiThreadTest"); } [Fact] public void MultiThreadBufferFullTest() { CreateLoggerFromConfiguration("AWSNLogGroupMultiThreadBufferFullTest.config"); Logger = LogManager.GetLogger("loggerMultiThreadBufferFull"); MultiThreadBufferFullTestGroup("AWSNLogGroupMultiThreadBufferFullTest"); } [Fact] public void MessageHasToBeBrokenUp() { string logGroupName = "AWSNLogGroupEventSizeExceededTest"; CreateLoggerFromConfiguration("AWSNLogGroupEventSizeExceededTest.config"); Logger = LogManager.GetLogger("loggerRegularEventSizeExceeded"); // This will get broken up into 3 CloudWatch Log messages Logger.Debug(new string('a', 600000)); Logger.Debug(LASTMESSAGE); GetLogEventsResponse getLogEventsResponse = new GetLogEventsResponse(); if (NotifyLoggingCompleted(logGroupName, "LASTMESSAGE")) { DescribeLogStreamsResponse describeLogstreamsResponse = Client.DescribeLogStreamsAsync(new DescribeLogStreamsRequest { Descending = true, LogGroupName = logGroupName, OrderBy = "LastEventTime" }).Result; // Wait for the large messages to propagate Thread.Sleep(5000); getLogEventsResponse = Client.GetLogEventsAsync(new GetLogEventsRequest { LogGroupName = logGroupName, LogStreamName = describeLogstreamsResponse.LogStreams[0].LogStreamName }).Result; } _testFixture.LogGroupNameList.Add(logGroupName); Assert.Equal(4, getLogEventsResponse.Events.Count); } protected override void LogMessages(int count) { for (int i = 0; i < count-1; i++) { Logger.Debug(string.Format("Test logging message {0} NLog, Thread Id:{1}", i, Thread.CurrentThread.ManagedThreadId)); } Logger.Debug(LASTMESSAGE); } } #endregion }
97
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AWS.Logger.Test")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f7986868-9d7e-4df6-a57e-e79e38ad166d")]
19
aws-logging-dotnet
aws
C#
using System; using System.Threading; using Amazon.CloudWatchLogs.Model; using AWS.Logger.SeriLog; using AWS.Logger.TestUtils; using Microsoft.Extensions.Configuration; using Serilog; using Xunit; namespace AWS.Logger.SeriLog.Tests { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. // In the Build tab select "Produce outputs on build". public class SeriLoggerTestClass : BaseTestClass { public SeriLoggerTestClass(TestFixture testFixture) : base(testFixture) { } private void CreateLoggerFromConfiguration(string configurationFile) { var configuration = new ConfigurationBuilder() .AddJsonFile(configurationFile) .Build(); Log.Logger = new LoggerConfiguration(). ReadFrom.Configuration(configuration). WriteTo.AWSSeriLog( configuration).CreateLogger(); } #region Test Cases [Fact] public void SeriLogger() { CreateLoggerFromConfiguration("AWSSeriLogGroup.json"); SimpleLoggingTest("AWSSeriLogGroup"); } [Fact] public void MultiThreadTest() { CreateLoggerFromConfiguration("AWSSeriLogGroupMultiThreadTest.json"); MultiThreadTestGroup("AWSSeriLogGroupMultiThreadTest"); } [Fact] public void MultiThreadBufferFullTest() { CreateLoggerFromConfiguration("AWSSeriLogGroupMultiThreadBufferFullTest.json"); MultiThreadBufferFullTestGroup("AWSSeriLogGroupMultiThreadBufferFullTest"); } [Fact] public void RestrictedToMinimumLevelTest() { string logGroupName = "AWSSeriLogGroupRestrictedtoMinimumLevel"; // Create logger var configuration = new ConfigurationBuilder() .AddJsonFile("AWSSeriLogGroupRestrictedToMinimumLevel.json") .Build(); Log.Logger = new LoggerConfiguration(). ReadFrom.Configuration(configuration).CreateLogger(); ExecuteRestrictedToMinimumLevelTest(logGroupName); } private void ExecuteRestrictedToMinimumLevelTest(string logGroupName) { // Log 4 Debug messages for (int i = 0; i < 3; i++) { Log.Debug(string.Format("Test logging message {0} SeriLog, Thread Id:{1}", i, Thread.CurrentThread.ManagedThreadId)); } // Log 5 Error messages for (int i = 0; i < 5; i++) { Log.Error(string.Format("Test logging message {0} SeriLog, Thread Id:{1}", i, Thread.CurrentThread.ManagedThreadId)); } Log.Error(LASTMESSAGE); GetLogEventsResponse getLogEventsResponse = new GetLogEventsResponse(); if (NotifyLoggingCompleted("AWSSeriLogGroupRestrictedtoMinimumLevel", "LASTMESSAGE")) { DescribeLogStreamsResponse describeLogstreamsResponse = Client.DescribeLogStreamsAsync(new DescribeLogStreamsRequest { Descending = true, LogGroupName = logGroupName, OrderBy = "LastEventTime" }).Result; getLogEventsResponse = Client.GetLogEventsAsync(new GetLogEventsRequest { LogGroupName = logGroupName, LogStreamName = describeLogstreamsResponse.LogStreams[0].LogStreamName }).Result; } Assert.Equal(6, getLogEventsResponse.Events.Count); } /// <summary> /// This method posts debug messages onto CloudWatchLogs. /// </summary> /// <param name="count">The number of messages that would be posted onto CloudWatchLogs</param> protected override void LogMessages(int count) { for (int i = 0; i < count - 1; i++) { Log.Debug(string.Format("Test logging message {0} SeriLog, Thread Id:{1}", i, Thread.CurrentThread.ManagedThreadId)); } Log.Debug(LASTMESSAGE); } #endregion } }
117
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AWS.Logger.SeriLog.Tests")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f7986868-9d7e-4df6-a57e-e79e38ad166d")]
19
aws-logging-dotnet
aws
C#
using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace AWS.Logger.TestUtils { public abstract class BaseTestClass : IClassFixture<TestFixture> { public const int SIMPLELOGTEST_COUNT = 10; public const int MULTITHREADTEST_COUNT = 200; public const int THREAD_WAITTIME = 10; public const int THREAD_COUNT = 2; public const string LASTMESSAGE = "LASTMESSAGE"; public const string CUSTOMSTREAMSUFFIX = "Custom"; public const string CUSTOMSTREAMPREFIX = "CustomPrefix"; public TestFixture _testFixture; public AmazonCloudWatchLogsClient Client; public BaseTestClass(TestFixture testFixture) { _testFixture = testFixture; Client = new AmazonCloudWatchLogsClient(Amazon.RegionEndpoint.USWest2); } protected bool NotifyLoggingCompleted(string logGroupName, string filterPattern) { Stopwatch timer = new Stopwatch(); timer.Start(); while (timer.Elapsed < TimeSpan.FromSeconds(THREAD_WAITTIME)) { Thread.Sleep(500); if (FilterPatternExists(logGroupName, filterPattern)) { break; } } return FilterPatternExists(logGroupName, filterPattern); } protected bool FilterPatternExists(string logGroupName, string filterPattern) { DescribeLogStreamsResponse describeLogstreamsResponse; try { describeLogstreamsResponse = Client. DescribeLogStreamsAsync(new DescribeLogStreamsRequest { Descending = true, LogGroupName = logGroupName, OrderBy = "LastEventTime" }).Result; } catch (Exception) { return false; } if (describeLogstreamsResponse.LogStreams.Count > 0) { List<string> logStreamNames = new List<string>(); logStreamNames.Add(describeLogstreamsResponse.LogStreams[0].LogStreamName); FilterLogEventsResponse filterLogEventsResponse = Client. FilterLogEventsAsync(new FilterLogEventsRequest { FilterPattern = filterPattern, LogGroupName = logGroupName, LogStreamNames = logStreamNames }).Result; return filterLogEventsResponse.Events.Count > 0; } else { return false; } } protected abstract void LogMessages(int count); protected void SimpleLoggingTest(string logGroupName) { LogMessages(SIMPLELOGTEST_COUNT); GetLogEventsResponse getLogEventsResponse = new GetLogEventsResponse(); if (NotifyLoggingCompleted(logGroupName, "LASTMESSAGE")) { DescribeLogStreamsResponse describeLogstreamsResponse = Client.DescribeLogStreamsAsync(new DescribeLogStreamsRequest { Descending = true, LogGroupName = logGroupName, OrderBy = "LastEventTime" }).Result; getLogEventsResponse = Client.GetLogEventsAsync(new GetLogEventsRequest { LogGroupName = logGroupName, LogStreamName = describeLogstreamsResponse.LogStreams[0].LogStreamName }).Result; var customStreamSuffix = describeLogstreamsResponse.LogStreams[0].LogStreamName.Split('-').Last().Trim(); Assert.Equal(CUSTOMSTREAMSUFFIX, customStreamSuffix); var customStreamPrefix = describeLogstreamsResponse.LogStreams[0].LogStreamName.Split('-').First().Trim(); Assert.Equal(CUSTOMSTREAMPREFIX, customStreamPrefix); } Assert.Equal(SIMPLELOGTEST_COUNT, getLogEventsResponse.Events.Count()); _testFixture.LogGroupNameList.Add(logGroupName); } protected void MultiThreadTestGroup(string logGroupName) { var tasks = new List<Task>(); var streamNames = new List<string>(); var count = MULTITHREADTEST_COUNT; var totalCount = 0; for (int i = 0; i < THREAD_COUNT; i++) { tasks.Add(Task.Factory.StartNew(() => LogMessages(count))); totalCount = totalCount + count; } Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(THREAD_WAITTIME)); int testCount = -1; if (NotifyLoggingCompleted(logGroupName, "LASTMESSAGE")) { DescribeLogStreamsResponse describeLogstreamsResponse = Client.DescribeLogStreamsAsync(new DescribeLogStreamsRequest { Descending = true, LogGroupName = logGroupName, OrderBy = "LastEventTime" }).Result; if (describeLogstreamsResponse.LogStreams.Count > 0) { testCount = 0; foreach (var logStream in describeLogstreamsResponse.LogStreams) { GetLogEventsResponse getLogEventsResponse = Client.GetLogEventsAsync(new GetLogEventsRequest { LogGroupName = logGroupName, LogStreamName = logStream.LogStreamName }).Result; if (getLogEventsResponse != null) { testCount += getLogEventsResponse.Events.Count(); } } } } Assert.Equal(totalCount, testCount); _testFixture.LogGroupNameList.Add(logGroupName); } protected void MultiThreadBufferFullTestGroup(string logGroupName) { var tasks = new List<Task>(); var streamNames = new List<string>(); var count = MULTITHREADTEST_COUNT; var totalCount = 0; for (int i = 0; i < THREAD_COUNT; i++) { tasks.Add(Task.Factory.StartNew(() => LogMessages(count))); totalCount = totalCount + count; } Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(THREAD_WAITTIME)); Assert.True(NotifyLoggingCompleted(logGroupName, "maximum")); _testFixture.LogGroupNameList.Add(logGroupName); } } }
190
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using System.Threading; using System.Diagnostics; namespace AWS.Logger.TestUtils { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. // In the Build tab select "Produce outputs on build". //TestClass to dispose test generated LogGroups. public class TestFixture : IDisposable { public List<string> LogGroupNameList; public TestFixture() { AmazonCloudWatchLogsClient Client = new AmazonCloudWatchLogsClient(Amazon.RegionEndpoint.USWest2); LogGroupNameList = new List<string>(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { AmazonCloudWatchLogsClient Client = new AmazonCloudWatchLogsClient(Amazon.RegionEndpoint.USWest2); foreach (var logGroupName in LogGroupNameList) { if (!(string.IsNullOrEmpty(logGroupName))) { DescribeLogGroupsResponse describeLogGroupsResponse = Client.DescribeLogGroupsAsync( new DescribeLogGroupsRequest { LogGroupNamePrefix = logGroupName }).Result; if (!(string.IsNullOrEmpty(describeLogGroupsResponse.LogGroups[0].LogGroupName))) { var response = Client.DeleteLogGroupAsync(new DeleteLogGroupRequest { LogGroupName = logGroupName }).Result; } } } } } }
61
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TestUtils")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("adff6031-0f8e-4eed-8e28-f29f0900bc11")]
19
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; using Xunit; using AWS.Logger; namespace AWS.Logger.UnitTests { public class AWSLoggerConfigTests { AWSLoggerConfig config; public AWSLoggerConfigTests() { config = new AWSLoggerConfig(); } [Fact] public void TestDefaultBatchSizeInBytes() { Assert.Equal(102400, config.BatchSizeInBytes); } [Fact] public void SetInvalidValueOnBatchSizeInBytes() { var exception = Record.Exception(() => config.BatchSizeInBytes = (int)Math.Pow(1024, 2) + 1); Assert.NotNull(exception); Assert.IsType<ArgumentException>(exception); } [Fact] public void SetValidValueOnBatchSizeInBytes() { var exception = Record.Exception(() => config.BatchSizeInBytes = (int)Math.Pow(1024, 2) - 1); Assert.Null(exception); } } }
39
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; using Amazon; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using AWS.Logger.Core; using AWS.Logger.TestUtils; using Xunit; using Xunit.Abstractions; namespace AWS.Logger.UnitTests { public class DisableLogGroupCreationTests : IClassFixture<TestFixture> { /*AmazonCloudWatchLogsClient client; */ public DisableLogGroupCreationTests(TestFixture testFixture, ITestOutputHelper output) { _testFixure = testFixture; _output = output; } private readonly TestFixture _testFixure; private readonly ITestOutputHelper _output; [Fact] public async Task TestCoreWithDisableLogGroupCreation() { var logGroupName = nameof(TestCoreWithDisableLogGroupCreation); using (var client = new AmazonCloudWatchLogsClient(RegionEndpoint.USWest2)) { var config = new AWSLoggerConfig(logGroupName ) { Region = RegionEndpoint.USWest2.SystemName, DisableLogGroupCreation = true, }; var resourceNotFoundPromise = new TaskCompletionSource<bool>(); // true means we saw expected exception; false otherwise var core = new AWSLoggerCore(config, "unit"); core.LogLibraryAlert += (sender, e) => { if (e.Exception is ResourceNotFoundException) { // saw EXPECTED exception. resourceNotFoundPromise.TrySetResult(true); } else if (e.Exception != null) { _output.WriteLine("Was not expecting to see exception: {0} @{1}", e.Exception, e.ServiceUrl); } }; var tsk = Task.Factory.StartNew(() => { core.AddMessage("Test message added at " + DateTimeOffset.UtcNow.ToString()); core.Flush(); }); await Task.WhenAny(tsk, resourceNotFoundPromise.Task).ConfigureAwait(false); resourceNotFoundPromise.TrySetResult(false); Assert.True(await resourceNotFoundPromise.Task); // now we create the log group, late. await client.CreateLogGroupAsync(new CreateLogGroupRequest { LogGroupName = logGroupName }); _testFixure.LogGroupNameList.Add(logGroupName); // wait for the flusher task to finish, which should actually proceed OK, now that we've created the expected log group. await tsk.ConfigureAwait(false); core.Close(); } } [Fact] public void TestCoreWithoutDisableLogGroupCreation() { var logGroupName = nameof(TestCoreWithoutDisableLogGroupCreation) + DateTime.UtcNow.Ticks; // this one will have to be auto-created. using (var client = new AmazonCloudWatchLogsClient(RegionEndpoint.USWest2)) { var config = new AWSLoggerConfig(logGroupName) { Region = RegionEndpoint.USWest2.SystemName, DisableLogGroupCreation = false, }; var core = new AWSLoggerCore(config, "unit"); core.AddMessage("Test message added at " + DateTimeOffset.UtcNow.ToString()); core.Flush(); _testFixure.LogGroupNameList.Add(logGroupName); // let's enlist the auto-created group for deletion. core.Close(); } } } }
104
aws-logging-dotnet
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.Globalization; using System.Text; using Xunit; using AWS.Logger; using AWS.Logger.Core; namespace AWS.Logger.UnitTests { public class GenerateStreamNameTests { [Fact] public void DefaultConfig() { var config = new AWSLoggerConfig { }; var streamName = AWSLoggerCore.GenerateStreamName(config); var tokens = SplitStreamName(streamName); Assert.Equal(2, tokens.Length); Assert.True(IsTokenDate(tokens[0])); Assert.True(IsTokenGuid(tokens[1])); } [Fact] public void SuffixSet() { var config = new AWSLoggerConfig { LogStreamNameSuffix = "TheSuffix" }; var streamName = AWSLoggerCore.GenerateStreamName(config); var tokens = SplitStreamName(streamName); Assert.Equal(2, tokens.Length); Assert.True(IsTokenDate(tokens[0])); Assert.Equal(config.LogStreamNameSuffix, tokens[1]); } [Fact] public void PrefixSetSuffixAtDefault() { var config = new AWSLoggerConfig { LogStreamNamePrefix = "ThePrefix" }; var streamName = AWSLoggerCore.GenerateStreamName(config); var tokens = SplitStreamName(streamName); Assert.Equal(3, tokens.Length); Assert.Equal(config.LogStreamNamePrefix, tokens[0]); Assert.True(IsTokenDate(tokens[1])); Assert.True(IsTokenGuid(tokens[2])); } [Fact] public void PrefixSetSuffixSet() { var config = new AWSLoggerConfig { LogStreamNamePrefix = "ThePrefix", LogStreamNameSuffix = "TheSuffix" }; var streamName = AWSLoggerCore.GenerateStreamName(config); var tokens = SplitStreamName(streamName); Assert.Equal(3, tokens.Length); Assert.Equal(config.LogStreamNamePrefix, tokens[0]); Assert.True(IsTokenDate(tokens[1])); Assert.Equal(config.LogStreamNameSuffix, tokens[2]); } [Fact] public void PrefixSetSuffixSetToNull() { var config = new AWSLoggerConfig { LogStreamNamePrefix = "ThePrefix", LogStreamNameSuffix = null }; var streamName = AWSLoggerCore.GenerateStreamName(config); var tokens = SplitStreamName(streamName); Assert.Equal(2, tokens.Length); Assert.Equal(config.LogStreamNamePrefix, tokens[0]); Assert.True(IsTokenDate(tokens[1])); } [Fact] public void PrefixSetSuffixSetToEmptyString() { var config = new AWSLoggerConfig { LogStreamNamePrefix = "ThePrefix", LogStreamNameSuffix = string.Empty }; var streamName = AWSLoggerCore.GenerateStreamName(config); var tokens = SplitStreamName(streamName); Assert.Equal(2, tokens.Length); Assert.Equal(config.LogStreamNamePrefix, tokens[0]); Assert.True(IsTokenDate(tokens[1])); } private string[] SplitStreamName(string streamName) { const string searchToken = " - "; var tokens = new List<string>(); int currentPos = 0; int pos = streamName.IndexOf(searchToken); while(pos != -1) { tokens.Add(streamName.Substring(currentPos, pos - currentPos)); currentPos = pos + searchToken.Length; pos = streamName.IndexOf(searchToken, currentPos); } if(currentPos < streamName.Length) { tokens.Add(streamName.Substring(currentPos, streamName.Length - currentPos)); } return tokens.ToArray(); } private bool IsTokenDate(string token) { DateTime dt; return DateTime.TryParseExact(token, "yyyy/MM/ddTHH.mm.ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt); } private bool IsTokenGuid(string token) { Guid guid; return Guid.TryParse(token, out guid); } } }
151
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; using Xunit; using AWS.Logger.Core; namespace AWS.Logger.UnitTests { public class MessageSizeBreakupTests { [Fact] public void AsciiTest() { var message = new string('a', 240000); Assert.Single(AWSLoggerCore.BreakupMessage(message)); } [Fact] public void UnicodeCharTest() { var testChar = '∀'; var charCount = 240000; var message = new string(testChar, charCount); var bytesSize = Encoding.UTF8.GetByteCount(message); Assert.Equal((bytesSize / 256000) + 1, AWSLoggerCore.BreakupMessage(message).Count); } } }
31
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; using Amazon; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using AWS.Logger.TestUtils; using Xunit; namespace AWS.Logger.UnitTest { public class UnitTest:IClassFixture<TestFixture> { AmazonCloudWatchLogsClient client; TestFixture _testFixure; public UnitTest(TestFixture testFixture) { _testFixure = testFixture; } [Fact] public async Task RegexTest() { var logGroupName = "RegexTest"; var logStreamName = "TestMessage"; Regex invalid_sequence_token_regex = new Regex(@"The given sequenceToken is invalid. The next expected sequenceToken is: (\d+)"); client = new AmazonCloudWatchLogsClient(RegionEndpoint.USWest2); await client.CreateLogGroupAsync(new CreateLogGroupRequest { LogGroupName = logGroupName }); _testFixure.LogGroupNameList.Add(logGroupName); await client.CreateLogStreamAsync(new CreateLogStreamRequest { LogGroupName = logGroupName, LogStreamName = logStreamName }); var putlogEventsRequest = new PutLogEventsRequest { LogGroupName = logGroupName, LogStreamName = logStreamName, LogEvents = new List<InputLogEvent> { new InputLogEvent { Timestamp = DateTime.Now, Message = "Message1" } } }; var response = await client.PutLogEventsAsync(putlogEventsRequest); try { putlogEventsRequest.LogEvents = new List<InputLogEvent> { new InputLogEvent { Timestamp = DateTime.Now, Message = "Message2" } }; await client.PutLogEventsAsync(putlogEventsRequest); } catch (InvalidSequenceTokenException ex) { var regexResult = invalid_sequence_token_regex.Match(ex.Message); if (regexResult.Success) { Assert.Equal(regexResult.Groups[1].Value, response.NextSequenceToken); } } } } }
83
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTest")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0cdf585c-ced0-456f-95ea-f2aab8b9f4e7")]
19
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using Amazon.Util; using Amazon.Util.Internal; using Amazon.MobileAnalytics.MobileAnalyticsManager; using Amazon.Runtime.Internal; namespace Amazon.MobileAnalytics.MobileAnalyticsManager { /// <summary> /// Represents configuration for Mobile Analytics Manager. /// </summary> public partial class MobileAnalyticsManagerConfig { private const int defaultSessionTimeout = 5; private const int defaultMaxDBSize = 5242880; private const double defaultDBWarningThreshold = 0.9; private const int defaultMaxRequestSize = 102400; private const bool defaultAllowUseDataNetwork = false; /// <summary> /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig"/> /// </summary> public MobileAnalyticsManagerConfig() { SessionTimeout = defaultSessionTimeout; MaxDBSize = defaultMaxDBSize; DBWarningThreshold = defaultDBWarningThreshold; MaxRequestSize = defaultMaxRequestSize; AllowUseDataNetwork = defaultAllowUseDataNetwork; #if BCL ClientContextConfiguration = new ClientContextConfig(); #endif } #if BCL /// <summary> /// Client Context Configuration . <see cref="Amazon.Runtime.Internal.ClientContextConfig"/> /// </summary> public ClientContextConfig ClientContextConfiguration { get; set; } #endif /// <summary> /// If the app stays in background for a time greater than the SessionTimeout then Mobile Analytics client stops old session and /// creates a new session once app comes back to foreground. /// We recommend using values ranging from 5 to 10, /// </summary> /// <value>Default 5 seconds</value> public int SessionTimeout { get; set; } /// <summary> /// Gets the max size of the database used for local storage of events. Event Storage will ignore new /// events if the size of database exceed this size. Value is in Bytes. /// We recommend using values ranging from 1MB to 10MB /// </summary> /// <value>Default 5MB</value> public int MaxDBSize { get; set; } /// <summary> /// The Warning threshold. The values range between 0 - 1. If the values exceed beyond the threshold then the /// Warning logs will be generated. /// </summary> /// <value>Default 0.9</value> public double DBWarningThreshold { get; set; } /// <summary> /// The maximum size of the requests that can be submitted in every service call. Value can range between /// 1-512KB (expressed in long). Value is in Bytes. Attention: Do not use value larger than 512KB. May cause /// service to reject your Http request. /// </summary> /// <value>Default 100KB</value> public int MaxRequestSize { get; set; } /// <summary> /// A value indicating whether service call is allowed over data network /// Setting this property to true may increase customer's data usage. /// </summary> /// <value>Default false</value> public bool AllowUseDataNetwork { get; set; } } }
105
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections; using System.Collections.Generic; using System.Threading; using System; using Amazon.Runtime.Internal.Util; using Logger = Amazon.Runtime.Internal.Util.Logger; #if PCL || BCL45 using System.Threading.Tasks; #endif namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Amazon Mobile Analytics background runner. /// Background runner periodically calls delivery client to send events to server. /// </summary> public partial class BackgroundRunner { private static volatile bool ShouldStop = false; private Logger _logger = Logger.GetLogger(typeof(BackgroundRunner)); private object _lock = new object(); // Background thread wait time. Thread will sleep for the interval mention. Value is in Seconds. // Default 60 seconds. private const int BackgroundSubmissionWaitTime = 60; /// <summary> /// Instruct any running BackgroundRunner instances that they should stop running. /// </summary> public static void AbortBackgroundRunner() { ShouldStop = true; } } }
55
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Objects that represnets constants used in Mobile Analytics /// </summary> internal class Constants { // Event Type Constants --------------------------- public const string SESSION_START_EVENT_TYPE = "_session.start"; public const string SESSION_STOP_EVENT_TYPE = "_session.stop"; public const string SESSION_PAUSE_EVENT_TYPE = "_session.pause"; public const string SESSION_RESUME_EVENT_TYPE = "_session.resume"; } }
28
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Diagnostics.CodeAnalysis; // Identifier should not match keywords [module: SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Scope="type", Target="Amazon.MobileAnalytics.Model.Event", MessageId="Event")] // supress warning for implementing ISerializable interface [module: SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Scope="type", Target="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.EventStoreException")] // Keep MobileAnalyticsManager namespace [module: SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces", Scope = "type", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManager")] // supress warnings for catching general exception [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManager.#ResumeSession()")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManager.#PauseSession()")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.Session.#RetrieveSessionStorage()")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryClient.#EnqueueEventsForDeliveryAsync(Amazon.MobileAnalytics.Model.Event)")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.SQLiteEventStore.#GetEvents(System.String,System.Int32)")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.SQLiteEventStore.#DeleteEvent(System.Collections.Generic.List`1<System.String>)")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.SQLiteEventStore.#PutEvent(System.String,System.String)")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.SQLiteEventStore.#NumberOfEvents(System.String)")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.BackgroundRunner.#DoWork()")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.SQLiteEventStore.#SetupSQLiteEventStore()")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryClient.#SubmitEvents(System.Collections.Generic.List`1<System.String>,System.Collections.Generic.List`1<Amazon.MobileAnalytics.Model.Event>)")] [module: SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Scope="member", Target="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryClient.#EnqueueEventsForDelivery(Amazon.MobileAnalytics.Model.Event)")] [module: SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManager.#.cctor()")] [module: SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.ConnectivityPolicy.#HasNetworkConnectivity()")] [module: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Amazon.Runtime.Internal.ClientContext.#.ctor(System.String,Amazon.Runtime.Internal.ClientContextConfig)")] [module: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.Session.#.ctor(System.String,Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig)")] [module: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.SQLiteEventStore.#.ctor(Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig)")] [module: SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Scope = "member", Target = "Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.SQLiteEventStore.#.cctor()")]
50
aws-mobile-analytics-manager-net
aws
C#
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // using System; using System.Collections; using System.Collections.Generic; using System.Threading; using Amazon.Runtime; using Amazon.Util; using Amazon.Runtime.Internal; using Amazon.MobileAnalytics.MobileAnalyticsManager.Internal; using Amazon.Runtime.Internal.Util; namespace Amazon.MobileAnalytics.MobileAnalyticsManager { /// <summary> /// MobileAnalyticsManager in the entry point to recording analytic events for your application /// </summary> public partial class MobileAnalyticsManager { /// <summary> /// Gets or creates Mobile Analytics Manager instance. If the instance already exists, returns the instance; otherwise /// creates new instance and returns it. /// </summary> /// <param name="appID">Amazon Mobile Analytics Application ID.</param> /// <returns>Mobile Analytics Manager instance. </returns> public static MobileAnalyticsManager GetOrCreateInstance(string appID) { if (string.IsNullOrEmpty(appID)) throw new ArgumentNullException("appID"); return GetOrCreateInstanceHelper(appID, null, null, null); } /// <summary> /// Gets or creates Mobile Analytics Manager instance. If the instance already exists, returns the instance; otherwise /// creates new instance and returns it. /// </summary> /// <param name="appID">Amazon Mobile Analytics Application ID.</param> /// <param name="credentials">AWS Credentials.</param> /// <returns>Mobile Analytics Manager instance. </returns> public static MobileAnalyticsManager GetOrCreateInstance(string appID, AWSCredentials credentials) { if (string.IsNullOrEmpty(appID)) throw new ArgumentNullException("appID"); if (null == credentials) throw new ArgumentNullException("credentials"); return GetOrCreateInstanceHelper(appID, credentials, null, null); } /// <summary> /// Gets or creates Mobile Analytics Manager instance. If the instance already exists, returns the instance; otherwise /// creates new instance and returns it. /// </summary> /// <param name="appID">Amazon Mobile Analytics Application ID.</param> /// <param name="regionEndpoint">Region endpoint.</param> /// <returns>Mobile Analytics Manager instance. </returns> public static MobileAnalyticsManager GetOrCreateInstance(string appID, RegionEndpoint regionEndpoint) { if (string.IsNullOrEmpty(appID)) throw new ArgumentNullException("appID"); if (null == regionEndpoint) throw new ArgumentNullException("regionEndpoint"); return GetOrCreateInstanceHelper(appID, null, regionEndpoint, null); } /// <summary> /// Gets or creates Mobile Analytics Manager instance. If the instance already exists, returns the instance; otherwise /// creates new instance and returns it. /// </summary> /// <param name="appID">Amazon Mobile Analytics Application ID.</param> /// <param name="maConfig">Amazon Mobile Analytics Manager configuration.</param> /// <returns>Mobile Analytics Manager instance. </returns> public static MobileAnalyticsManager GetOrCreateInstance(string appID, MobileAnalyticsManagerConfig maConfig) { if (string.IsNullOrEmpty(appID)) throw new ArgumentNullException("appID"); if (null == maConfig) throw new ArgumentNullException("maConfig"); return GetOrCreateInstanceHelper(appID, null, null, maConfig); } #region private #if BCL static void ValidateParameters() { if (string.IsNullOrEmpty(AWSConfigs.ApplicationName)) { throw new ArgumentException("A valid application name needs to configured to use this API." + "The application name can be configured through app.config/web.config or by setting the Amazon.AWSConfigs.ApplicationName property."); } } #endif #endregion } }
109
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Threading; using Amazon.Runtime; using Amazon.Util; using Amazon.Runtime.Internal; using Amazon.MobileAnalytics.MobileAnalyticsManager.Internal; using Amazon.Runtime.Internal.Util; namespace Amazon.MobileAnalytics.MobileAnalyticsManager { /// <summary> /// MobileAnalyticsManager is the entry point to recording analytic events for your application /// </summary> public partial class MobileAnalyticsManager : IDisposable { private static Object _lock = new Object(); private static IDictionary<string, MobileAnalyticsManager> _instanceDictionary = new Dictionary<string, MobileAnalyticsManager>(); private Logger _logger = Logger.GetLogger(typeof(MobileAnalyticsManager)); private static BackgroundRunner _backgroundRunner = new BackgroundRunner(); #region constructor /// <summary> /// Gets or creates Mobile Analytics Manager instance. If the instance already exists, returns the instance; otherwise /// creates new instance and returns it. /// </summary> /// <param name="appID">Amazon Mobile Analytics Application ID.</param> /// <param name="credentials">AWS Credentials.</param> /// <param name="regionEndpoint">Region endpoint.</param> /// <param name="maConfig">Amazon Mobile Analytics Manager configuration.</param> /// <returns>Mobile Analytics Manager instance. </returns> public static MobileAnalyticsManager GetOrCreateInstance(string appID, AWSCredentials credentials, RegionEndpoint regionEndpoint, MobileAnalyticsManagerConfig maConfig) { if (string.IsNullOrEmpty(appID)) throw new ArgumentNullException("appID"); if (null == credentials) throw new ArgumentNullException("credentials"); if (null == regionEndpoint) throw new ArgumentNullException("regionEndpoint"); if (null == maConfig) throw new ArgumentNullException("maConfig"); return GetOrCreateInstanceHelper(appID, credentials, regionEndpoint, maConfig); } /// <summary> /// Gets or creates Mobile Analytics Manager instance. If the instance already exists, returns the instance; otherwise /// creates new instance and returns it. /// </summary> /// <param name="appID">Amazon Mobile Analytics Application ID.</param> /// <param name="credentials">AWS Credentials.</param> /// <param name="regionEndpoint">Region endpoint.</param> /// <returns>Mobile Analytics Manager instance.</returns> public static MobileAnalyticsManager GetOrCreateInstance(string appID, AWSCredentials credentials, RegionEndpoint regionEndpoint) { if (string.IsNullOrEmpty(appID)) throw new ArgumentNullException("appID"); if (null == credentials) throw new ArgumentNullException("credentials"); if (null == regionEndpoint) throw new ArgumentNullException("regionEndpoint"); MobileAnalyticsManagerConfig maConfig = new MobileAnalyticsManagerConfig(); return GetOrCreateInstanceHelper(appID, credentials, regionEndpoint, maConfig); } /// <summary> /// Gets Mobile Analytics Manager instance by Application ID. Returns Mobile Analytics Manager instance if it's found. /// Throws InvalidOperationException if the instance has not been instantiated. /// </summary> /// <param name="appID">Amazon Mobile Analytics Application ID.</param> /// <returns>The Mobile Analytics Manager instance.</returns> public static MobileAnalyticsManager GetInstance(string appID) { if (string.IsNullOrEmpty(appID)) throw new ArgumentNullException("appID"); MobileAnalyticsManager managerInstance = null; lock (_lock) { if (_instanceDictionary.TryGetValue(appID, out managerInstance)) { return managerInstance; } else { throw new InvalidOperationException("Cannot find MobileAnalyticsManager instance for appID " + appID + ". Please call GetOrCreateInstance() first."); } } } private static MobileAnalyticsManager GetOrCreateInstanceHelper(string appID, AWSCredentials credentials, RegionEndpoint regionEndpoint, MobileAnalyticsManagerConfig maConfig) { #if BCL ValidateParameters(); #endif MobileAnalyticsManager managerInstance = null; bool isNewInstance = false; lock (_lock) { if (_instanceDictionary.TryGetValue(appID, out managerInstance)) { return managerInstance; } else { managerInstance = new MobileAnalyticsManager(appID, credentials, regionEndpoint, maConfig); _instanceDictionary[appID] = managerInstance; isNewInstance = true; } } if (isNewInstance) { managerInstance.Session.Start(); } _backgroundRunner.StartWork(); return managerInstance; } private MobileAnalyticsManager(string appID, AWSCredentials credentials, RegionEndpoint regionEndpoint, MobileAnalyticsManagerConfig maConfig) { #if PCL this.ClientContext = new ClientContext(appID); #elif BCL if (null == maConfig) maConfig = new MobileAnalyticsManagerConfig(); this.ClientContext = new ClientContext(appID, maConfig.ClientContextConfiguration); #endif this.BackgroundDeliveryClient = new DeliveryClient(maConfig, ClientContext, credentials, regionEndpoint, this); this.Session = new Session(appID, maConfig); } #endregion #region public /// <summary> /// Pauses the current session. /// PauseSession() is the entry point into the Amazon Mobile Analytics SDK where sessions can be paused. Session is created and started immediately /// after instantiating the MobileAnalyticsManager object. The session remains active until it is paused. When in a paused state, the session time will /// not accumulate. When resuming a session, if enough time has elapsed from when the session is paused to when it's resumed, the session is ended and /// a new session is created and started. Otherwise, the paused session is resumed and the session time continues to accumulate. Currently session /// time out default value is 5 seconds. /// /// For example, on Android platform, when MobileAnalyticsManager is first instantiated, it creates Session 1. As the user transitions from activity to activity, the old /// activity will pause the current session, and the new activity will immediately resume the current session. In this case, Session 1 remains active /// and accumulates session time. The user continues to use the App for a total of 3 minutes, at which point, the user receives a phone call. /// When transitioning to the phone call, the current activity will pause the session and then transition to the phone app. In this case Session 1 /// remains paused while the phone call is in progress and session time does not accumulate. After completing the phone call a few minutes later, /// the user returns to the App and the activity will resume Session 1. Since enough time has elapsed since resuming Session 1, Session 1 will be ended /// with a play time of 3 minutes. Session 2 will then be immediately created and started. /// /// In order for MobileAnalyticsManager to track sessions, you must call the PauseSession() and ResumeSession() in each activity of your app. /// <example> /// The example below shows how to pause and resume session in Xamarin Android /// <code> ///public class MainActivity : Activity ///{ /// private static MobileAnalyticsManager _manager = null; /// /// protected override void OnCreate(Bundle bundle) /// { /// _manager = MobileAnalyticsManager.GetOrCreateInstance(YourAppId, YourCredential, RegionEndpoint.USEast1, YourConfig); /// base.OnCreate(bundle); /// } /// protected override void OnResume() /// { /// await _manager.ResumeSession(); /// base.OnResume(); /// } /// protected override void OnPause() /// { /// await _manager.PauseSession(); /// base.OnPause(); /// } ///} /// </code> /// </example> /// </summary> public void PauseSession() { try { Session.Pause(); } catch (Exception e) { _logger.Error(e, "An exception occurred when pause session."); MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when pausing session.", e, new List<Amazon.MobileAnalytics.Model.Event>()); OnRaiseErrorEvent(eventArgs); } } /// <summary> /// Resume the current session. /// ResumeSession() is the entry point into the Amazon Mobile Analytics SDK where sessions can be resumed. Session is created and started immediately /// after instantiating the MobileAnalyticsManager object. The session remains active until it is paused. When in a paused state, the session time will /// not accumulate. When resuming a session, if enough time has elapsed from when the session is paused to when it's resumed, the session is ended and /// a new session is created and started. Otherwise, the paused session is resumed and the session time continues to accumulate. Currently session /// time out default value is 5 seconds. /// /// For example, on Android platform, when MobileAnalyticsManager is first instantiated, it creates Session 1. As the user transitions from activity to activity, the old /// activity will pause the current session, and the new activity will immediately resume the current session. In this case, Session 1 remains active /// and accumulates session time. The user continues to use the App for a total of 3 minutes, at which point, the user receives a phone call. /// When transitioning to the phone call, the current activity will pause the session and then transition to the phone app. In this case Session 1 /// remains paused while the phone call is in progress and session time does not accumulate. After completing the phone call a few minutes later, /// the user returns to the App and the activity will resume Session 1. Since enough time has elapsed since resuming Session 1, Session 1 will be ended /// with a play time of 3 minutes. Session 2 will then be immediately created and started. /// /// In order for MobileAnalyticsManager to track sessions, you must call the PauseSession() and ResumeSession() in each activity of your app. /// <example> /// The example below shows how to pause and resume session in Xamarin Android /// <code> ///public class MainActivity : Activity ///{ /// private static MobileAnalyticsManager _manager = null; /// /// protected override void OnCreate(Bundle bundle) /// { /// _manager = MobileAnalyticsManager.GetOrCreateInstance(YourAppId, YourCredential, RegionEndpoint.USEast1, YourConfig); /// base.OnCreate(bundle); /// } /// protected override void OnResume() /// { /// await _manager.ResumeSession(); /// base.OnResume(); /// } /// protected override void OnPause() /// { /// await _manager.PauseSession(); /// base.OnPause(); /// } ///} /// </code> /// </example> /// </summary> public void ResumeSession() { try { Session.Resume(); } catch (Exception e) { _logger.Error(e, "An exception occurred when resume session."); MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when resuming session.", e, new List<Amazon.MobileAnalytics.Model.Event>()); OnRaiseErrorEvent(eventArgs); } } /// <summary> /// Records the custom event to the local persistent storage. Background thread will deliver the event later. /// </summary> /// <param name="customEvent">The Mobile Analytics event.</param> public void RecordEvent(CustomEvent customEvent) { if (null == customEvent) throw new ArgumentNullException("customEvent"); customEvent.Timestamp = AWSSDKUtils.CorrectedUtcNow; Amazon.MobileAnalytics.Model.Event modelEvent = customEvent.ConvertToMobileAnalyticsModelEvent(this.Session); BackgroundDeliveryClient.EnqueueEventsForDelivery(modelEvent); } /// <summary> /// Adds client context custom attribute /// Refer <a href="http://docs.aws.amazon.com/mobileanalytics/latest/ug/PutEvents.html" >Rest API</a> for more information /// </summary> /// <param name="key">Key.</param> /// <param name="value">Value.</param> public void AddCustomAttributeToClientContext(string key, string value) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (null == value) { throw new ArgumentNullException("value"); } ClientContext.AddCustomAttributes(key, value); } /// <summary> /// The event for MobileAnalyticsErrorEvent notifications. All subscribers will be notified /// when a new Mobile Analytics error event is raised. /// <para> /// The MobileAnalyticsErrorEvent is fired as error happens in Mobile Analytics Manager. /// The delegates attached to the event will be passed information detailing what is the error. /// For example, the error can be Amazon Mobile Analytics server return error, local event storage error, /// File I/O error etc. /// </para> /// The example below shows how to subscribe to this event. /// <example> /// 1. Define a method with a signature similar to this one: /// <code> /// private void errorHandler(object sender, MobileAnalyticsErrorEventArgs args) /// { /// Console.WriteLine(args); /// } /// </code> /// 2. Add this method to the MobileAnalyticsErrorEvent delegate's invocation list /// <code> /// _manager = MobileAnalyticsManager.GetOrCreateInstance(YourAppId, YourCredential, RegionEndpoint.USEast1, YourConfig); /// _manager.MobileAnalyticsErrorEvent += errorHandler; /// </code> /// </example> /// </summary> public event EventHandler<MobileAnalyticsErrorEventArgs> MobileAnalyticsErrorEvent; #endregion #region internal internal Session Session { get; set; } internal ClientContext ClientContext { get; set; } internal IDeliveryClient BackgroundDeliveryClient { get; private set; } internal static IDictionary<string, MobileAnalyticsManager> CopyOfInstanceDictionary { get { lock (_lock) { return new Dictionary<string, MobileAnalyticsManager>(_instanceDictionary); } } } internal void OnRaiseErrorEvent(MobileAnalyticsErrorEventArgs eventArgs) { AWSSDKUtils.InvokeInBackground(MobileAnalyticsErrorEvent, eventArgs, this); } #endregion #region Dispose Pattern Implementation /// <summary> /// Implement the dispose pattern /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Implement the dispose pattern /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposing) { this.Session.Dispose(); this.BackgroundDeliveryClient.Dispose(); } } #endregion } /// <summary> /// Encapsulates the information needed to notify /// errors of Mobile Analytics Manager. /// </summary> public class MobileAnalyticsErrorEventArgs : EventArgs { /// <summary> /// The constructor of MobileAnalyticsErrorEventArgs /// </summary> /// <param name="className">The class name where the error is caught.</param> /// <param name="errorMessage">The message that describes reason of the error.</param> /// <param name="exception">The exception thrown in Mobile Analytics Manager.</param> /// <param name="undeliveredEvents">The list of events that caused the error. This is a list of low level event objects. This list might be empty if the error is not caused by mal-formatted events.</param> internal MobileAnalyticsErrorEventArgs(string className, string errorMessage, Exception exception, List<Amazon.MobileAnalytics.Model.Event> undeliveredEvents) { if (null == className) throw new ArgumentNullException("className"); if (null == errorMessage) throw new ArgumentNullException("errorMessage"); if (null == exception) throw new ArgumentNullException("exception"); if (null == undeliveredEvents) throw new ArgumentNullException("undeliveredEvents"); this.ClassName = className; this.ErrorMessage = errorMessage; this.Exception = exception; this.UndeliveredEvents = undeliveredEvents; } /// <summary> /// The class name where the error is caught. /// </summary> public string ClassName { get; set; } /// <summary> /// The message that describes reason of the error. /// </summary> public string ErrorMessage { get; set; } /// <summary> /// The exception thrown in Mobile Analytics Manager. /// </summary> public Exception Exception { get; set; } /// <summary> /// The list of events that caused the error. This is a list of low level event objects. /// This list might be empty if the error is not caused by mal-formatted events. /// </summary> public List<Amazon.MobileAnalytics.Model.Event> UndeliveredEvents { get; set; } } }
444
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Net; using Amazon.Runtime; using Amazon.MobileAnalytics.MobileAnalyticsManager; using Amazon.MobileAnalytics; using Amazon.MobileAnalytics.Model; using ThirdParty.Json.LitJson; using Amazon.Runtime.Internal.Util; using Amazon.Runtime.Internal; #if PCL || BCL45 using System.Threading.Tasks; #endif namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Delivery client periodically sends events in local persistent storage to Mobile Analytics server. /// Once the events is delivered successfully, those events would be deleted from local storage. /// </summary> public partial class DeliveryClient : IDeliveryClient { /// <summary> /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryClient"/> class. /// </summary> /// <param name="policyFactory">An instance of IDeliveryPolicyFactory. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IDeliveryPolicyFactory"/></param> /// <param name="maConfig">Mobile Analytics Manager configuration. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig"/></param> /// <param name="clientContext">An instance of ClientContext. <see cref="Amazon.Runtime.Internal.ClientContext"/></param> /// <param name="credentials">An instance of Credentials. <see cref="Amazon.Runtime.AWSCredentials"/></param> /// <param name="regionEndPoint">Region endpoint. <see cref="Amazon.RegionEndpoint"/></param> /// <param name="maManager">Mobile Analytics Manager instance. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManager"/></param> public DeliveryClient(IDeliveryPolicyFactory policyFactory, MobileAnalyticsManagerConfig maConfig, ClientContext clientContext, AWSCredentials credentials, RegionEndpoint regionEndPoint, MobileAnalyticsManager maManager) { _policyFactory = policyFactory; _deliveryPolicies = new List<IDeliveryPolicy>(); _deliveryPolicies.Add(_policyFactory.NewConnectivityPolicy()); _clientContext = clientContext; _appID = clientContext.AppID; _maConfig = maConfig; _eventStore = new SQLiteEventStore(maConfig); _maManager = maManager; if (null == credentials && null == regionEndPoint) { _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(); } else if (null == credentials) { _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(regionEndPoint); } else if (null == regionEndPoint) { _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials); } else { _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint); } } } }
84
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Net; using Amazon.Runtime; using Amazon.MobileAnalytics.MobileAnalyticsManager; using Amazon.MobileAnalytics; using Amazon.MobileAnalytics.Model; using ThirdParty.Json.LitJson; using Amazon.Runtime.Internal.Util; using Amazon.Runtime.Internal; #if PCL || BCL45 using System.Threading.Tasks; #endif namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Delivery client periodically sends events in local persistent storage to Mobile Analytics server. /// Once the events is delivered successfully, those events would be deleted from local storage. /// </summary> public partial class DeliveryClient : IDeliveryClient { private Logger _logger = Logger.GetLogger(typeof(DeliveryClient)); private object _deliveryLock = new object(); private bool _deliveryInProgress = false; private readonly IDeliveryPolicyFactory _policyFactory; private List<IDeliveryPolicy> _deliveryPolicies; private IEventStore _eventStore; private AmazonMobileAnalyticsClient _mobileAnalyticsLowLevelClient; private ClientContext _clientContext; private string _appID; private MobileAnalyticsManagerConfig _maConfig; private MobileAnalyticsManager _maManager; private const int MAX_ALLOWED_SELECTS = 200; /// <summary> /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryClient"/> class. /// </summary> /// <param name="maConfig">Mobile Analytics Manager configuration. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig"/></param> /// <param name="clientContext">An instance of ClientContext. <see cref="Amazon.Runtime.Internal.ClientContext"/></param> /// <param name="credentials">An instance of Credentials. <see cref="Amazon.Runtime.AWSCredentials"/></param> /// <param name="regionEndPoint">Region endpoint. <see cref="Amazon.RegionEndpoint"/></param> /// <param name="maManager">Mobile Analytics Manager instance. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManager"/></param> public DeliveryClient(MobileAnalyticsManagerConfig maConfig, ClientContext clientContext, AWSCredentials credentials, RegionEndpoint regionEndPoint, MobileAnalyticsManager maManager) : this(new DeliveryPolicyFactory(maConfig.AllowUseDataNetwork), maConfig, clientContext, credentials, regionEndPoint, maManager) { } #if BCL35 /// <summary> /// Enqueues the events for delivery. The event is stored in an instance of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IEventStore"/>. /// </summary> /// <param name="eventObject">Event object.<see cref="Amazon.MobileAnalytics.Model.Event"/></param> public void EnqueueEventsForDelivery(Amazon.MobileAnalytics.Model.Event eventObject) { ThreadPool.QueueUserWorkItem(new WaitCallback(delegate { EnqueueEventsHelper(eventObject); })); } /// <summary> /// Attempts the delivery. /// Delivery will fail if any of the policies IsAllowed() returns false. /// The delivery are attmpted in batches of fixed size. To increase or decrease the size, /// you can override MaxRequestSize in MobileAnalyticsManagerConfig.<see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig"/> /// </summary> public void AttemptDelivery() { lock (_deliveryLock) { if (_deliveryInProgress) { _logger.InfoFormat("Delivery already in progress, failing new delivery"); return; } _deliveryInProgress = true; } //validate all the policies before attempting the delivery foreach (IDeliveryPolicy policy in _deliveryPolicies) { if (!policy.IsAllowed()) { _logger.InfoFormat("Policy restriction: {0}", policy.GetType().Name); lock (_deliveryLock) { _deliveryInProgress = false; } return; } } List<JsonData> allEventList = _eventStore.GetEvents(_appID, MAX_ALLOWED_SELECTS); if (allEventList.Count == 0) { _logger.InfoFormat("No Events to deliver."); lock (_deliveryLock) { _deliveryInProgress = false; } return; } List<string> submitEventsIdList = new List<string>(); List<Amazon.MobileAnalytics.Model.Event> submitEventsList = new List<Amazon.MobileAnalytics.Model.Event>(); long submitEventsLength = 0L; foreach (JsonData eventData in allEventList) { string eventString = (string)eventData["event"]; submitEventsLength += eventString.Length; if (submitEventsLength < _maConfig.MaxRequestSize) { try { Amazon.MobileAnalytics.Model.Event _analyticsEvent = JsonMapper.ToObject<Amazon.MobileAnalytics.Model.Event>(eventString); submitEventsList.Add(_analyticsEvent); } catch (JsonException e) { _logger.Error(e, "Could not load event from event store, discarding."); } submitEventsIdList.Add(eventData["id"].ToString()); } else { SubmitEvents(submitEventsIdList, submitEventsList); submitEventsIdList = new List<string>(); submitEventsList = new List<Amazon.MobileAnalytics.Model.Event>(); submitEventsLength = 0L; } } if (submitEventsLength > 0) SubmitEvents(submitEventsIdList, submitEventsList); } /// <summary> /// Submits a single batch of events to the service. /// </summary> /// <param name="rowIds">Row identifiers. The list of rowId, that is unique identifier of each event.</param> /// <param name="eventList">The list of events that need to be submitted.</param> private void SubmitEvents(List<string> rowIds, List<Amazon.MobileAnalytics.Model.Event> eventList) { PutEventsRequest putRequest = new PutEventsRequest(); putRequest.Events = eventList; putRequest.ClientContext = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes(_clientContext.ToJsonString())); putRequest.ClientContextEncoding = "base64"; _logger.DebugFormat("Client Context is : {0}", _clientContext.ToJsonString()); PutEventsResponse resp = null; try { resp = _mobileAnalyticsLowLevelClient.PutEvents(putRequest); } catch (AmazonMobileAnalyticsException e) { _logger.Error(e, "An AmazonMobileAnalyticsException occurred while sending Amazon Mobile Analytics request: error code is {0} ; error type is {1} ; request id is {2} ; status code is {3} ; error message is {4}", e.ErrorCode, e.ErrorType, e.RequestId, e.StatusCode, e.Message); // Delete events in any of the three error codes. if (e.StatusCode == HttpStatusCode.BadRequest && (e.ErrorCode.Equals("ValidationException", StringComparison.CurrentCultureIgnoreCase) || e.ErrorCode.Equals("SerializationException", StringComparison.CurrentCultureIgnoreCase) || e.ErrorCode.Equals("BadRequestException", StringComparison.CurrentCultureIgnoreCase))) { MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "Amazon Mobile Analytics Service returned an error.", e, eventList); _maManager.OnRaiseErrorEvent(eventArgs); _logger.InfoFormat("The error code is not retriable. Delete {0} events from local storage.", rowIds.Count); _eventStore.DeleteEvent(rowIds); } else { MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "Amazon Mobile Analytics Service returned an error.", e, new List<Amazon.MobileAnalytics.Model.Event>()); _maManager.OnRaiseErrorEvent(eventArgs); } } catch (AmazonServiceException e) { _logger.Error(e, "An AmazonServiceException occurred while sending Amazon Mobile Analytics request: error code is {0} ; error type is {1} ; request id is {2} ; status code is {3} ; error message is {4} ", e.ErrorCode, e.ErrorType, e.RequestId, e.StatusCode, e.Message); MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "Amazon Web Service returned an error.", e, new List<Amazon.MobileAnalytics.Model.Event>()); _maManager.OnRaiseErrorEvent(eventArgs); } catch (Exception e) { _logger.Error(e, "An exception occurred while sending Amazon Mobile Analytics request."); MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when sending request to Amazon Mobile Analytics.", e, new List<Amazon.MobileAnalytics.Model.Event>()); _maManager.OnRaiseErrorEvent(eventArgs); } finally { if (resp != null && resp.HttpStatusCode == HttpStatusCode.Accepted) { _logger.InfoFormat("Mobile Analytics client successfully delivered {0} events to service. Delete those events from local storage.", rowIds.Count); _eventStore.DeleteEvent(rowIds); } lock (_deliveryLock) { _deliveryInProgress = false; } } } #endif #if PCL || BCL45 /// <summary> /// Enqueues the events for delivery. The event is stored in an instance of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IEventStore"/>. /// </summary> /// <param name="eventObject">Event object.<see cref="Amazon.MobileAnalytics.Model.Event"/></param> public void EnqueueEventsForDelivery(Amazon.MobileAnalytics.Model.Event eventObject) { Task.Run(() => { EnqueueEventsHelper(eventObject); }); } /// <summary> /// Attempts the delivery. /// Delivery will fail if any of the policies IsAllowed() returns false. /// The delivery are attmpted in batches of fixed size. To increase or decrease the size, /// you can override MaxRequestSize in MobileAnalyticsManagerConfig.<see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig"/> /// </summary> public async Task AttemptDeliveryAsync() { lock (_deliveryLock) { if (_deliveryInProgress) { _logger.InfoFormat("Delivery already in progress, failing new delivery"); return; } _deliveryInProgress = true; } //validate all the policies before attempting the delivery foreach (IDeliveryPolicy policy in _deliveryPolicies) { if (!policy.IsAllowed()) { _logger.InfoFormat("Policy restriction: {0}", policy.GetType().Name); lock (_deliveryLock) { _deliveryInProgress = false; } return; } } List<JsonData> allEventList = _eventStore.GetEvents(_appID, MAX_ALLOWED_SELECTS); if (allEventList == null || allEventList.Count == 0) { _logger.InfoFormat("No Events to deliver."); lock (_deliveryLock) { _deliveryInProgress = false; } return; } List<string> submitEventsIdList = new List<string>(); List<Amazon.MobileAnalytics.Model.Event> submitEventsList = new List<Amazon.MobileAnalytics.Model.Event>(); long submitEventsLength = 0L; foreach (JsonData eventData in allEventList) { string eventString = (string)eventData["event"]; submitEventsLength += eventString.Length; if (submitEventsLength < _maConfig.MaxRequestSize) { Amazon.MobileAnalytics.Model.Event _analyticsEvent = JsonMapper.ToObject<Amazon.MobileAnalytics.Model.Event>(eventString); submitEventsIdList.Add(eventData["id"].ToString()); submitEventsList.Add(_analyticsEvent); } else { await SubmitEvents(submitEventsIdList, submitEventsList).ConfigureAwait(false); submitEventsIdList = new List<string>(); submitEventsList = new List<Amazon.MobileAnalytics.Model.Event>(); submitEventsLength = 0L; } } if (submitEventsLength > 0) await SubmitEvents(submitEventsIdList, submitEventsList).ConfigureAwait(false); } /// <summary> /// Submits a single batch of events to the service. /// </summary> /// <param name="rowIds">Row identifiers. The list of rowId, that is unique identifier of each event.</param> /// <param name="eventList">The list of events that need to be submitted.</param> #if BCL35 private void SubmitEvents(List<string> rowIds, List<Amazon.MobileAnalytics.Model.Event> eventList) #elif PCL || BCL45 private async Task SubmitEvents(List<string> rowIds, List<Amazon.MobileAnalytics.Model.Event> eventList) #endif { PutEventsRequest putRequest = new PutEventsRequest(); putRequest.Events = eventList; putRequest.ClientContext = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes(_clientContext.ToJsonString())); putRequest.ClientContextEncoding = "base64"; _logger.DebugFormat("Client Context is : {0}", _clientContext.ToJsonString()); PutEventsResponse resp = null; try { resp = await _mobileAnalyticsLowLevelClient.PutEventsAsync(putRequest).ConfigureAwait(false); } catch (AmazonMobileAnalyticsException e) { _logger.Error(e, "An AmazonMobileAnalyticsException occurred while sending Amazon Mobile Analytics request: error code is {0} ; error type is {1} ; request id is {2} ; status code is {3} ; error message is {4}", e.ErrorCode, e.ErrorType, e.RequestId, e.StatusCode, e.Message); // Delete events in any of the three error codes. if (e.StatusCode == HttpStatusCode.BadRequest && (e.ErrorCode.Equals("ValidationException", StringComparison.CurrentCultureIgnoreCase) || e.ErrorCode.Equals("SerializationException", StringComparison.CurrentCultureIgnoreCase) || e.ErrorCode.Equals("BadRequestException", StringComparison.CurrentCultureIgnoreCase))) { MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "Amazon Mobile Analytics Service returned an error.", e, eventList); _maManager.OnRaiseErrorEvent(eventArgs); _logger.InfoFormat("The error code is not retriable. Delete {0} events from local storage.", rowIds.Count); _eventStore.DeleteEvent(rowIds); } else { MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "Amazon Mobile Analytics Service returned an error.", e, new List<Amazon.MobileAnalytics.Model.Event>()); _maManager.OnRaiseErrorEvent(eventArgs); } } catch (AmazonServiceException e) { _logger.Error(e, "An AmazonServiceException occurred while sending Amazon Mobile Analytics request: error code is {0} ; error type is {1} ; request id is {2} ; status code is {3} ; error message is {4} ", e.ErrorCode, e.ErrorType, e.RequestId, e.StatusCode, e.Message); MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "Amazon Web Service returned an error.", e, new List<Amazon.MobileAnalytics.Model.Event>()); _maManager.OnRaiseErrorEvent(eventArgs); } catch (Exception e) { _logger.Error(e, "An exception occurred while sending Amazon Mobile Analytics request."); MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when sending request to Amazon Mobile Analytics.", e, new List<Amazon.MobileAnalytics.Model.Event>()); _maManager.OnRaiseErrorEvent(eventArgs); } finally { if (resp != null && resp.HttpStatusCode == HttpStatusCode.Accepted) { _logger.InfoFormat("Mobile Analytics client successfully delivered {0} events to service. Delete those events from local storage.", rowIds.Count); _eventStore.DeleteEvent(rowIds); } lock (_deliveryLock) { _deliveryInProgress = false; } } } #endif private void EnqueueEventsHelper(Amazon.MobileAnalytics.Model.Event eventObject) { string eventString = null; try { eventString = JsonMapper.ToJson(eventObject); } catch (Exception e) { _logger.Error(e, "An exception occurred when converting low level client event to json string."); List<Amazon.MobileAnalytics.Model.Event> eventList = new List<Amazon.MobileAnalytics.Model.Event>(); eventList.Add(eventObject); MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when converting low level client event to json string.", e, eventList); _maManager.OnRaiseErrorEvent(eventArgs); } if (null != eventString) { try { _eventStore.PutEvent(eventString, _appID); } catch (Exception e) { _logger.Error(e, "Event {0} was not stored.", eventObject.EventType); MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when storing event into event store.", e, new List<Amazon.MobileAnalytics.Model.Event>()); _maManager.OnRaiseErrorEvent(eventArgs); } _logger.DebugFormat("Event {0} is queued for delivery", eventObject.EventType); } } #region dispose pattern implementation /// <summary> /// Dispose pattern implementation /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose pattern implementation /// </summary> /// <param name="disposing">if disposing</param> protected virtual void Dispose(bool disposing) { if(disposing) { _eventStore.Dispose(); _mobileAnalyticsLowLevelClient.Dispose(); } } #endregion } }
451
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Exception thrown by the SDK for errors that occur within the Mobile Analytics event store. /// </summary> public class EventStoreException : Exception { /// <summary> /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.EventStoreException"/> /// </summary> /// <param name="message">Exception message.</param> public EventStoreException(string message) : base(message) { } /// <summary> /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.EventStoreException"/> /// </summary> /// <param name="message">Exception message.</param> /// <param name="innerException">Inner exception.</param> public EventStoreException(string message, Exception innerException) : base(message, innerException) { } } }
43
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.MobileAnalytics.Model; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// The interface for delivery client. /// </summary> public partial interface IDeliveryClient : IDisposable { /// <summary> /// Enqueues the events for delivery. The event is stored in an <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IEventStore"/>. /// </summary> /// <param name="eventObject">Event object. <see cref="Amazon.MobileAnalytics.Model.Event"/></param> void EnqueueEventsForDelivery(Amazon.MobileAnalytics.Model.Event eventObject); } }
34
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using ThirdParty.Json.LitJson; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// The interface for managing events storage. /// </summary> public interface IEventStore:IDisposable { /// <summary> /// Add an event to the store. /// </summary> /// <param name="value">Amazon Mobile Analytics event in string.</param> /// <param name="appId">Amazon Mobile Analytics App ID.</param> /// <returns><c>true</c>, if event was put, <c>false</c> otherwise.</returns> void PutEvent(string value, string appId); /// <summary> /// Get events from the Event Store /// </summary> /// <param name="appid">Amazon Mobile Analytics App Id.</param> /// <param name="maxAllowed">Max number of events is allowed to return.</param> /// <returns>The events as a List of <see cref="ThirdParty.Json.LitJson.JsonData"/>.</returns> List<JsonData> GetEvents(string appid, int maxAllowed); /// <summary> /// Deletes a list of events. /// </summary> /// <param name="rowIds">List of row identifiers.</param> /// <returns><c>true</c>, if events was deleted, <c>false</c> otherwise.</returns> void DeleteEvent(List<string> rowIds); /// <summary> /// Gets Numbers the of events. /// </summary> /// <param name="appId">Amazon Mobile Analytics App Identifier.</param> /// <returns>The number of events.</returns> long NumberOfEvents(string appId); /// <summary> /// Gets the size of the database. /// </summary> /// <returns>The database size.</returns> long DatabaseSize { get; } } }
69
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using Amazon.MobileAnalytics.Model; using ThirdParty.Json.LitJson; using Amazon.MobileAnalytics.MobileAnalyticsManager; using Amazon.Util; using Amazon.Runtime.Internal.Util; using Amazon.Util.Internal; using System.Globalization; using System.Data.SQLite; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Implementation of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IEventStore"/>. /// The object stores Mobile Analytic events in SQLite database. /// </summary> public partial class SQLiteEventStore : IEventStore { /// <summary> /// Implements the Dispose pattern /// </summary> /// <param name="disposing">Whether this object is being disposed via a call to Dispose /// or garbage collected.</param> protected virtual void Dispose(bool disposing) { } /// <summary> /// Sets up SQLite database. /// </summary> private void SetupSQLiteEventStore() { this.DBfileFullPath = InternalSDKUtils.DetermineAppLocalStoragePath(dbFileName); string vacuumCommand = "PRAGMA auto_vacuum = 1"; string sqlCommand = string.Format(CultureInfo.InvariantCulture, "CREATE TABLE IF NOT EXISTS {0} ({1} TEXT NOT NULL,{2} TEXT NOT NULL UNIQUE,{3} TEXT NOT NULL, {4} INTEGER NOT NULL DEFAULT 0 )", TABLE_NAME, EVENT_COLUMN_NAME, EVENT_ID_COLUMN_NAME, MA_APP_ID_COLUMN_NAME, EVENT_DELIVERY_ATTEMPT_COUNT_COLUMN_NAME); lock (_lock) { using (var connection = new SQLiteConnection("Data Source=" + this.DBfileFullPath + ";Version=3;")) { try { if (!File.Exists(this.DBfileFullPath)) { string directory = Path.GetDirectoryName(this.DBfileFullPath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } SQLiteConnection.CreateFile(this.DBfileFullPath); } connection.Open(); using (var command = new SQLiteCommand(vacuumCommand, connection)) { command.ExecuteNonQuery(); } using (var command = new SQLiteCommand(sqlCommand, connection)) { command.ExecuteNonQuery(); } } finally { if (null != connection) connection.Close(); } } } } /// <summary> /// Add an event to the store. /// </summary> /// <param name="eventString">Amazon Mobile Analytics event in string.</param> /// <param name="appID">Amazon Mobile Analytics App ID.</param> [System.Security.SecuritySafeCritical] public void PutEvent(string eventString, string appID) { long currentDatabaseSize = this.DatabaseSize; if (currentDatabaseSize >= _maConfig.MaxDBSize) { InvalidOperationException e = new InvalidOperationException(); _logger.Error(e, "The database size has exceeded the threshold limit. Unable to insert any new events"); } else if ((double)currentDatabaseSize / (double)_maConfig.MaxDBSize >= _maConfig.DBWarningThreshold) { _logger.InfoFormat("The database size is almost full"); } else { string sqlCommand = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0} ({1},{2},{3}) values(@event,@id,@appID)", TABLE_NAME, EVENT_COLUMN_NAME, EVENT_ID_COLUMN_NAME, MA_APP_ID_COLUMN_NAME); lock (_lock) { using (var connection = new SQLiteConnection("Data Source=" + this.DBfileFullPath + ";Version=3;")) { try { connection.Open(); using (var command = new SQLiteCommand(sqlCommand, connection)) { command.Parameters.Add(new SQLiteParameter("@event", eventString)); command.Parameters.Add(new SQLiteParameter("@id", Guid.NewGuid().ToString())); command.Parameters.Add(new SQLiteParameter("@appID", appID)); command.ExecuteNonQuery(); } } finally { if (null != connection) connection.Close(); } } } } } /// <summary> /// Deletes a list of events. /// </summary> /// <param name="rowIds">List of row identifiers.</param> [System.Security.SecuritySafeCritical] public void DeleteEvent(List<string> rowIds) { string ids = string.Format(CultureInfo.InvariantCulture, "'{0}'", string.Join("', '", rowIds.ToArray())); string sqlCommand = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE {1} IN ({2})", TABLE_NAME, EVENT_ID_COLUMN_NAME, ids); SQLiteConnection connection = null; lock (_lock) { using (connection = new SQLiteConnection("Data Source=" + this.DBfileFullPath + ";Version=3;")) { try { connection.Open(); using (var command = new SQLiteCommand(sqlCommand, connection)) { command.ExecuteNonQuery(); } } finally { if (null != connection) connection.Close(); } } } } /// <summary> /// Get events from the Event Store /// </summary> /// <param name="appID">Amazon Mobile Analytics App Id.</param> /// <param name="maxAllowed">Max number of events is allowed to return.</param> /// <returns>The events as a List of <see cref="ThirdParty.Json.LitJson.JsonData"/>.</returns> [System.Security.SecuritySafeCritical] public List<JsonData> GetEvents(string appID, int maxAllowed) { List<JsonData> eventList = new List<JsonData>(); string sqlCommand = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0} WHERE {1} = @appID ORDER BY {2}, ROWID LIMIT {3} ", TABLE_NAME, MA_APP_ID_COLUMN_NAME, EVENT_DELIVERY_ATTEMPT_COUNT_COLUMN_NAME, maxAllowed); lock (_lock) { using (var connection = new SQLiteConnection("Data Source=" + this.DBfileFullPath + ";Version=3;")) { try { connection.Open(); using (var command = new SQLiteCommand(sqlCommand, connection)) { command.Parameters.Add(new SQLiteParameter("@appID", appID)); using (var reader = command.ExecuteReader()) { while (reader.Read()) { JsonData data = new JsonData(); data["id"] = reader[EVENT_ID_COLUMN_NAME].ToString(); data["event"] = reader[EVENT_COLUMN_NAME.ToUpperInvariant()].ToString(); data["appID"] = reader[MA_APP_ID_COLUMN_NAME].ToString(); eventList.Add(data); } } } } finally { if (null != connection) connection.Close(); } } } return eventList; } /// <summary> /// Gets Numbers the of events. /// </summary> /// <param name="appID">Amazon Mobile Analytics App Identifier.</param> /// <returns>The number of events.</returns> [System.Security.SecuritySafeCritical] public long NumberOfEvents(string appID) { long count = 0; string sqlCommand = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT(*) C FROM {0} where {1} = @appID", TABLE_NAME, MA_APP_ID_COLUMN_NAME); using (var connection = new SQLiteConnection("Data Source=" + this.DBfileFullPath + ";Version=3;")) { try { connection.Open(); using (var command = new SQLiteCommand(sqlCommand, connection)) { command.Parameters.Add(new SQLiteParameter("@appID", appID)); using (var reader = command.ExecuteReader()) { while (reader.Read()) { count = (long)reader["C"]; } } } } finally { if (null != connection) connection.Close(); } } return count; } /// <summary> /// Gets the size of the database. /// </summary> /// <returns>The database size.</returns> public long DatabaseSize { get { FileInfo fileInfo = new FileInfo(this.DBfileFullPath); return fileInfo.Length; } } } }
274
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Logger = Amazon.Runtime.Internal.Util.Logger; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Implementation of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IEventStore"/>. /// The object stores Mobile Analytic events in SQLite database. /// </summary> [System.Security.SecuritySafeCritical] public partial class SQLiteEventStore : IEventStore { private Logger _logger = Logger.GetLogger(typeof(SQLiteEventStore)); private const String TABLE_NAME = "ma_events"; private const String EVENT_COLUMN_NAME = "ma_event"; private const String EVENT_ID_COLUMN_NAME = "ma_event_id"; private const String EVENT_DELIVERY_ATTEMPT_COUNT_COLUMN_NAME = "ma_delivery_attempt_count"; private const String MA_APP_ID_COLUMN_NAME = "ma_app_id"; private const String TABLE_ROWID = "ROWID"; private const String DB_SIZE_KEY = "MAX_DB_SIZE"; private const String DB_WARNING_THRESHOLD_KEY = "DB_WARNING_THRESHOLD"; private const String dbFileName = "mobile_analytic_event.db"; // platform specific db file path private static object _lock = new object(); private MobileAnalyticsManagerConfig _maConfig; #pragma warning disable 414 private bool _isDisposed; #pragma warning restore 414 /// <summary> /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.SQLiteEventStore"/> /// </summary> /// <param name="maConfig">Mobile Analytics Manager Configuration.</param> public SQLiteEventStore(MobileAnalyticsManagerConfig maConfig) { _maConfig = maConfig; SetupSQLiteEventStore(); } #if PCL static SQLiteEventStore() { SQLitePCL.Batteries.Init(); } #endif /// <summary> /// Get the SQLite Event Store's database file full path. /// </summary> /// <returns> The database file full path. </returns> public string DBfileFullPath { get; internal set; } /// <summary> /// Disposes of all managed and unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } } }
87
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Net; using Amazon.Util.Internal.PlatformServices; using Amazon.Runtime.Internal.Util; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// An object for determining whether the delivery client should send events /// to mobile analytics service by checking the network status. /// </summary> public partial class ConnectivityPolicy : IDeliveryPolicy { /// <summary> /// Determines whether this instance has network connectivity. /// </summary> /// <returns><c>true</c> if this instance has network connectivity; otherwise, <c>false</c>.</returns> private bool HasNetworkConnectivity() { return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); } } }
39
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Net; using Amazon.Util.Internal.PlatformServices; using Amazon.Runtime.Internal.Util; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// An object for determining whether the delivery client should send events /// to mobile analytics service by checking the network status. /// </summary> public partial class ConnectivityPolicy : IDeliveryPolicy { private readonly bool IsDataAllowed; private Logger _logger = Logger.GetLogger(typeof(ConnectivityPolicy)); /// <summary> /// Initializes a new instance of the /// <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.ConnectivityPolicy"/> class. /// </summary> /// <param name="IsDataAllowed">If set to <c>true</c> polciy will allow the delivery on data network.</param> public ConnectivityPolicy(bool IsDataAllowed) { this.IsDataAllowed = IsDataAllowed; } /// <summary> /// Determines whether this policy allows the delivery of the events or not. /// </summary> /// <returns>true</returns> /// <c>false</c> public bool IsAllowed() { return this.HasNetworkConnectivity(); } } }
53
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.MobileAnalytics; using Amazon.MobileAnalytics.MobileAnalyticsManager; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Object that creates delivery policy. /// </summary> public partial class DeliveryPolicyFactory : IDeliveryPolicyFactory { private readonly bool IsDataNetworkAllowed; /// <summary> /// Initializes a new instance of the /// <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryPolicyFactory"/> class. /// </summary> /// <param name="IsDataNetworkAllowed">If set to <c>true</c> connectivity policy will allow delivery on data network.</param> public DeliveryPolicyFactory (bool IsDataNetworkAllowed) { this.IsDataNetworkAllowed = IsDataNetworkAllowed; } /// <summary> /// returns a new connectivity policy. /// </summary> /// <returns>instance of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IDeliveryPolicy"/>, which checks for network connectivity</returns> public IDeliveryPolicy NewConnectivityPolicy() { return new ConnectivityPolicy(this.IsDataNetworkAllowed); } } }
52
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// This interface is for delivery policy that determines whether delivery client should send events /// to Mobile Analytics service. /// </summary> public partial interface IDeliveryPolicy { /// <summary> /// Determines whether this policy allows the delivery of the events or not. /// </summary> /// <returns><c>true</c> if this policy allows the delivery of events; otherwise, <c>false</c>.</returns> bool IsAllowed(); } }
35
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Interface for creating delivery policy. /// </summary> public partial interface IDeliveryPolicyFactory { /// <summary> /// Returns a new connectivity policy. /// </summary> /// <returns>instance of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IDeliveryPolicy"/>, which checks network connectivity</returns> IDeliveryPolicy NewConnectivityPolicy(); } }
33
aws-mobile-analytics-manager-net
aws
C#
#if BCL35 /* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// The interface for delivery client. /// </summary> public partial interface IDeliveryClient { /// <summary> /// Attempts the delivery of events from local store to service. /// </summary> void AttemptDelivery(); } } #endif
30
aws-mobile-analytics-manager-net
aws
C#
#if BCL45 /* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// The interface for delivery client. /// </summary> public partial interface IDeliveryClient { /// <summary> /// Attempts the delivery of events from local store to service. /// </summary> System.Threading.Tasks.Task AttemptDeliveryAsync(); } } #endif
30
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections; using System.Collections.Generic; using System; using System.Collections.ObjectModel; using Amazon.MobileAnalytics.MobileAnalyticsManager; using Amazon.Util; using Amazon.MobileAnalytics.MobileAnalyticsManager.Internal; namespace Amazon.MobileAnalytics.MobileAnalyticsManager { /// <summary> /// Represents any useful event you wish to record in your application. /// <example> /// The example below shows how to use CustomEvent /// <code> /// CustomEvent customEvent = new CustomEvent("level_complete"); /// /// customEvent.AddAttribute("LevelName","Level1"); /// customEvent.AddAttribute("Successful","True"); /// customEvent.AddMetric("Score",12345); /// customEvent.AddMetric("TimeInLevel",64); /// /// analyticsManager.RecordEvent(customEvent); /// </code> /// </example> /// </summary> public class CustomEvent : IEvent { /// <summary> /// Event type string that defines event type. /// </summary> internal string EventType { get; set; } /// <summary> /// Dictionary that stores global attribute for specific event type. /// </summary> private static Dictionary<string, Dictionary<string,string>> _eventTypeGlobalAttributes = new Dictionary<string,Dictionary<string,string>>(); /// <summary> /// Dictionary that stores global metric for specific event type. /// </summary> private static Dictionary<string, Dictionary<string,double>> _eventTypeGlobalMetrics = new Dictionary<string, Dictionary<string,double>>(); /// <summary> /// Dictionary that stores global attribute for all event type. /// </summary> private static Dictionary<string,string> _globalAttributes = new Dictionary<string,string>(); /// <summary> /// Dictionary that stores global metric for all event type. /// </summary> private static Dictionary<string,double> _globalMetrics = new Dictionary<string,double>(); /// <summary> /// Dictionary that stores attribute for this event only. /// </summary> private Dictionary<string,string> _attributes = new Dictionary<string,string>(); /// <summary> /// Dictionary that stores metric for this event only. /// </summary> private Dictionary<string,double> _metrics = new Dictionary<string,double>(); /// <summary> /// Unique Identifier of Session /// </summary> internal string SessionId {get;set;} /// <summary> /// Duration of the session in milliseconds. /// </summary> internal long Duration { get; set; } /// <summary> /// Start time stamp of seesion. /// </summary> internal DateTime StartTimestamp {get;set;} /// <summary> /// Stop time stamp of session. /// </summary> internal DateTime? StopTimestamp { get; set; } /// <summary> /// Timestamp of when event is recorded. /// </summary> internal DateTime Timestamp { get; set; } /// <summary> /// Lock that protects global attribute and metric. /// </summary> private static Object _globalLock = new Object(); /// <summary> /// Lock that protects attribute and metric. /// </summary> private Object _lock = new Object(); private const int MAX_KEY_SIZE = 50; private const int MAX_ATTRIB_VALUE_SIZE = 255; #region constructor /// <summary> /// Initializes a new instance of the /// <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.CustomEvent"/> class. /// </summary> /// <param name="eventType">Event type.</param> public CustomEvent(string eventType) { if (null == eventType) throw new ArgumentNullException("eventType"); this.EventType = eventType; } #endregion /// <summary> /// Converts to mobile analytics model event. <see cref="Amazon.MobileAnalytics.Model.Event"/> /// </summary> /// <returns>The to mobile analytics model event.</returns> /// <param name="session">Session. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.Session"/></param> internal virtual Amazon.MobileAnalytics.Model.Event ConvertToMobileAnalyticsModelEvent(Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.Session session) { Amazon.MobileAnalytics.Model.Event modelEvent = new Amazon.MobileAnalytics.Model.Event(); this.StartTimestamp = session.StartTime; this.SessionId = session.SessionId; // assign session info from custom event to model event modelEvent.EventType = this.EventType; modelEvent.Session = new Amazon.MobileAnalytics.Model.Session(); modelEvent.Session.Id = session.SessionId; modelEvent.Session.StartTimestampUtc = session.StartTime; if (session.StopTime != null) modelEvent.Session.StopTimestampUtc = session.StopTime.Value; if(this.EventType == Constants.SESSION_STOP_EVENT_TYPE) { modelEvent.Session.StopTimestampUtc = this.StopTimestamp.Value; modelEvent.Session.Duration = this.Duration; } lock(_globalLock) { AddDict(_globalAttributes,modelEvent.Attributes); if(_eventTypeGlobalAttributes.ContainsKey(EventType)) { AddDict(_eventTypeGlobalAttributes[EventType],modelEvent.Attributes); } AddDict(_globalMetrics,modelEvent.Metrics); if(_eventTypeGlobalMetrics.ContainsKey(EventType)) { AddDict(_eventTypeGlobalMetrics[EventType],modelEvent.Metrics); } } lock(_lock) { AddDict(_attributes,modelEvent.Attributes); AddDict(_metrics,modelEvent.Metrics); } modelEvent.TimestampUtc = Timestamp; modelEvent.Version = "v2.0"; return modelEvent; } #region attribute /// <summary> /// Adds the attribute. /// </summary> /// <param name="attributeName">Attribute name. Max name length is 50.</param> /// <param name="attributeValue">Attribute value. Max value length is 255.</param> public void AddAttribute(string attributeName, string attributeValue) { if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } if (null == attributeValue) { throw new ArgumentNullException("attributeValue"); } if(attributeName.Length > MAX_KEY_SIZE) { throw new ArgumentException("Length of attributeName " + attributeName+" is more than " + MAX_KEY_SIZE); } if(attributeValue.Length > MAX_ATTRIB_VALUE_SIZE) { throw new ArgumentException("Length of attributeValue is more than " + MAX_ATTRIB_VALUE_SIZE); } lock(_lock) { _attributes[attributeName] = attributeValue; } } /// <summary> /// Determines whether this instance has attribute the specified attributeName. /// </summary> /// <param name="attributeName">Attribute name.</param> /// <returns>Return true if the event has the attribute, else false.</returns> public bool HasAttribute(string attributeName) { if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } bool ret = false; lock(_lock) { ret = _attributes.ContainsKey(attributeName); } return ret; } /// <summary> /// Gets the attribute. /// </summary> /// <param name="attributeName">Attribute name.</param> /// <returns>The attribute. Return null of attribute doesn't exist.</returns> public string GetAttribute(string attributeName) { if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } string ret = null; lock(_lock) { if(attributeName.Contains(attributeName)) ret = _attributes[attributeName]; } return ret; } /// <summary> /// Gets copy of all attributes. /// </summary> /// <returns>Copy of all the attributes.</returns> public IDictionary<string, string> AllAttributes { get { IDictionary<string,string> ret; lock(_lock) { ret = CopyDict(_attributes); } return ret; } } #endregion #region metric /// <summary> /// Adds the metric. /// </summary> /// <param name="metricName">Metric name. Max length is 50.</param> /// <param name="metricValue">Metric value.</param> public void AddMetric(string metricName, double metricValue) { if(string.IsNullOrEmpty(metricName)) { throw new ArgumentNullException("metricName"); } if(metricName.Length > MAX_KEY_SIZE) { throw new ArgumentException("length of the metricName " + metricName+" is more than " + MAX_KEY_SIZE); } lock(_lock) { _metrics[metricName] = metricValue; } } /// <summary> /// Determines whether this instance has metric the specified metricName. /// </summary> /// <param name="metricName">Metric name.</param> /// <returns>Return true if the event has the attribute, else false.</returns> public bool HasMetric(string metricName) { if(string.IsNullOrEmpty(metricName)) { throw new ArgumentNullException("metricName"); } bool ret = false; lock(_lock) { ret = _metrics.ContainsKey(metricName); } return ret; } /// <summary> /// Gets the metric. /// </summary> /// <param name="metricName">Metric name.</param> /// <returns>The metric. Return null of metric doesn't exist.</returns> public double? GetMetric(string metricName) { if(string.IsNullOrEmpty(metricName)) { throw new ArgumentNullException("metricName"); } double? ret = null; lock(_lock) { if(_metrics.ContainsKey(metricName)) ret = _metrics[metricName]; } return ret; } /// <summary> /// Gets copy of all metrics. /// </summary> /// <returns>Copy of all the metrics.</returns> public IDictionary<string, double> AllMetrics { get { IDictionary<string,double> ret; lock(_lock) { ret = CopyDict(_metrics); } return ret; } } #endregion #region gloablattribute /// <summary> /// Adds the global attribute, which is valid for all events. /// </summary> /// <param name="attributeName">Attribute name. Max length is 50.</param> /// <param name="attributeValue">Attribute value. Max length is 255.</param> public void AddGlobalAttribute(string attributeName, string attributeValue) { if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } if( null == attributeValue) { throw new ArgumentNullException("attributeValue"); } if(attributeName.Length > MAX_KEY_SIZE) { throw new ArgumentException("Length of attributeName " + attributeName+" is more than " + MAX_KEY_SIZE); } if(attributeValue.Length > MAX_ATTRIB_VALUE_SIZE) { throw new ArgumentException("Length of attributeValue is more than " + MAX_ATTRIB_VALUE_SIZE); } lock(_globalLock) { _globalAttributes[attributeName] = attributeValue; } } /// <summary> /// Adds the global attribute, which is valid to some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="attributeName">Attribute name. Max length is 50.</param> /// <param name="attributeValue">Attribute value. Max length is 255.</param> public void AddGlobalAttribute(string eventType, string attributeName, string attributeValue) { if(string.IsNullOrEmpty(eventType)) { throw new ArgumentNullException("eventType"); } if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } if( null == attributeValue) { throw new ArgumentNullException("attributeValue"); } if(attributeName.Length > MAX_KEY_SIZE) { throw new ArgumentException("Length of attributeName " + attributeName+" is more than " + MAX_KEY_SIZE); } if(attributeValue.Length > MAX_ATTRIB_VALUE_SIZE) { throw new ArgumentException("Length of attributeValue is more than " + MAX_ATTRIB_VALUE_SIZE); } lock(_globalLock) { if(!_eventTypeGlobalAttributes.ContainsKey(eventType)) { _eventTypeGlobalAttributes.Add(eventType,new Dictionary<string, string>()); _eventTypeGlobalAttributes[eventType].Add(attributeName, attributeValue); } else if(_eventTypeGlobalAttributes.ContainsKey(eventType) && !_eventTypeGlobalAttributes[eventType].ContainsKey(attributeName)) { _eventTypeGlobalAttributes[eventType].Add(attributeName, attributeValue); } } } /// <summary> /// Removes the global attribute, which is valid for all events. /// </summary> /// <param name="attributeName">Attribute name.</param> public void RemoveGlobalAttribute(string attributeName) { if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } lock(_globalLock) { if(_globalAttributes.ContainsKey(attributeName)) { _globalAttributes.Remove(attributeName); } } } /// <summary> /// Removes the global attribute, which is valid to some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="attributeName">Attribute name.</param> public void RemoveGlobalAttribute(string eventType, string attributeName) { if(string.IsNullOrEmpty(eventType)) { throw new ArgumentNullException("eventType"); } if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } lock(_globalLock) { if(_eventTypeGlobalAttributes.ContainsKey(eventType) && _eventTypeGlobalAttributes[eventType].ContainsKey(attributeName)) { _eventTypeGlobalAttributes[eventType].Remove(attributeName); } } } /// <summary> /// Gets the global attribute, which is valid for all events. /// </summary> /// <param name="attributeName">Attribute name.</param> /// <returns>The global attribute. Return null if attribute doesn't exist.</returns> public string GetGlobalAttribute(string attributeName) { if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } string ret = null; lock(_globalLock) { if(_globalAttributes.ContainsKey(attributeName)) { ret = _globalAttributes[attributeName]; } } return ret; } /// <summary> /// Gets the global attribute, which is valid for some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="attributeName">Attribute name.</param> /// <returns>The global attribute. Return null if attribute doesn't exist. </returns> public string GetGlobalAttribute(string eventType, string attributeName) { if(string.IsNullOrEmpty(eventType)) { throw new ArgumentNullException("eventType"); } if(string.IsNullOrEmpty(attributeName)) { throw new ArgumentNullException("attributeName"); } string ret = null; lock(_globalLock) { if(_eventTypeGlobalAttributes.ContainsKey(eventType) && _eventTypeGlobalAttributes[eventType].ContainsKey(attributeName)) { ret = _eventTypeGlobalAttributes[eventType][attributeName]; } } return ret; } #endregion #region globalmetric /// <summary> /// Adds the global metric, which is valid for all events. /// </summary> /// <param name="metricName">Metric name. Max length is 50.</param> /// <param name="metricValue">Metric value.</param> public void AddGlobalMetric(string metricName, double metricValue) { if(string.IsNullOrEmpty(metricName)) { throw new ArgumentNullException("metricName"); } if(metricName.Length > MAX_KEY_SIZE) { throw new ArgumentException("Length of the metricName " + metricName+" is more than " + MAX_KEY_SIZE); } lock(_globalLock) { _globalMetrics[metricName] = metricValue; } } /// <summary> /// Adds the global metric, which is valid for some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="metricName">Metric name. Max length is 50.</param> /// <param name="metricValue">Metric value.</param> public void AddGlobalMetric(string eventType, string metricName, double metricValue) { if(string.IsNullOrEmpty(eventType)) { throw new ArgumentNullException("eventType"); } if(string.IsNullOrEmpty(metricName)) { throw new ArgumentNullException("metricName"); } if(metricName.Length > MAX_KEY_SIZE) { throw new ArgumentException("Length of the metricName " + metricName+" is more than " + MAX_KEY_SIZE); } lock(_globalLock) { if(!_eventTypeGlobalMetrics.ContainsKey(eventType)) { _eventTypeGlobalMetrics.Add(eventType,new Dictionary<string, double>()); _eventTypeGlobalMetrics[eventType][metricName] = metricValue; return; } else if(_eventTypeGlobalMetrics.ContainsKey(eventType)) { _eventTypeGlobalMetrics[eventType][metricName] = metricValue; return; } } } /// <summary> /// Removes the global metric, which is valid for all events. /// </summary> /// <param name="metricName">Metric name.</param> public void RemoveGlobalMetric(string metricName) { if(string.IsNullOrEmpty(metricName)) { throw new ArgumentNullException("metricName"); } lock(_globalLock) { if(_globalMetrics.ContainsKey(metricName)) { _globalMetrics.Remove(metricName); } } } /// <summary> /// Removes the global metric, which is valid for some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="metricName">Metric name.</param> public void RemoveGlobalMetric(string eventType,string metricName) { if(string.IsNullOrEmpty(eventType)) { throw new ArgumentNullException("eventType"); } if(string.IsNullOrEmpty(metricName)) { throw new ArgumentNullException("metricName"); } lock(_globalLock) { if(_eventTypeGlobalMetrics.ContainsKey(eventType) && _eventTypeGlobalMetrics[eventType].ContainsKey(metricName)) { _eventTypeGlobalMetrics[eventType].Remove(metricName); } } } /// <summary> /// Gets the global metric, which is valid for all events. /// </summary> /// <returns>The global metric. Return null if metric doesn't exist.</returns> /// <param name="metricName">Metric name.</param> public double? GetGlobalMetric(string metricName) { if(string.IsNullOrEmpty(metricName)) { throw new ArgumentNullException("metricName"); } double? ret = null; lock(_globalLock) { if(_globalMetrics.ContainsKey(metricName)) ret = _globalMetrics[metricName]; } return ret; } /// <summary> /// Gets the global metric, which is valid for some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="metricName">Metric name.</param> /// <returns>The global metric. Return null if metric doesn't exist. </returns> public double? GetGlobalMetric(string eventType, string metricName) { if(string.IsNullOrEmpty(eventType)) { throw new ArgumentNullException("eventType"); } if(string.IsNullOrEmpty(metricName)) { throw new ArgumentNullException("metricName"); } double? ret = null; lock(_globalLock) { if(_eventTypeGlobalMetrics.ContainsKey(eventType) && _eventTypeGlobalMetrics[eventType].ContainsKey(metricName)) { ret = _eventTypeGlobalMetrics[eventType][metricName]; } } return ret; } #endregion #region util private static void AddDict<T, S>(Dictionary<T, S> srcDict, Dictionary<T, S> dstDict) { if(srcDict == null) { throw new ArgumentNullException("srcDict"); } if (dstDict == null) { throw new ArgumentNullException("dstDict"); } foreach (var item in srcDict) { dstDict[item.Key] = item.Value; } } private static Dictionary<T, S> CopyDict<T, S>(Dictionary<T, S> srcDict) { if(srcDict == null) { throw new ArgumentNullException("srcDict"); } Dictionary<T, S> dstDict = new Dictionary<T, S>(); foreach (var item in srcDict) { dstDict.Add(item.Key, item.Value); } return dstDict; } #endregion } }
768
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections; using System.Collections.Generic; using Amazon.MobileAnalytics.MobileAnalyticsManager.Internal; using System; namespace Amazon.MobileAnalytics.MobileAnalyticsManager { /// <summary> /// Interface for Mobile Analytics Event. /// </summary> public interface IEvent { #region attribute /// <summary> /// Adds the attribute. /// </summary> /// <param name="attributeName">Attribute name. Max name length is 50.</param> /// <param name="attributeValue">Attribute value. Max value length is 255.</param> void AddAttribute(string attributeName, string attributeValue); /// <summary> /// Determines whether this instance has attribute the specified attributeName. /// </summary> /// <returns><c>true</c> if this instance has attribute the specified attributeName; otherwise, <c>false</c>.</returns> /// <param name="attributeName">Attribute name.</param> bool HasAttribute(string attributeName); /// <summary> /// Gets the attribute. /// </summary> /// <returns>The attribute. Return null if the attribute doesn't exist.</returns> /// <param name="attributeName">Attribute name.</param> string GetAttribute(string attributeName); /// <summary> /// Gets all attributes. /// </summary> /// <returns>All the attributes.</returns> IDictionary<string, string> AllAttributes { get; } #endregion #region metric /// <summary> /// Adds the metric. /// </summary> /// <param name="metricName">Metric name. Max length is 50.</param> /// <param name="metricValue">Metric value.</param> void AddMetric(string metricName, double metricValue); /// <summary> /// Determines whether this instance has metric the specified metricName. /// </summary> /// <returns><c>true</c> if this instance has metric the specified metricName; otherwise, <c>false</c>.</returns> /// <param name="metricName">Metric name.</param> bool HasMetric(string metricName); /// <summary> /// Gets the metric. /// </summary> /// <returns>The metric. Return null if metric doesn't exist.</returns> /// <param name="metricName">Metric name.</param> double? GetMetric(string metricName); /// <summary> /// Gets all metrics. /// </summary> /// <returns>All the metrics.</returns> IDictionary<string, double> AllMetrics { get; } #endregion #region gloablattribute /// <summary> /// Adds the global attribute, which is valid for all events. /// </summary> /// <param name="attributeName">Attribute name. Max length is 50.</param> /// <param name="attributeValue">Attribute value. Max length is 255.</param> void AddGlobalAttribute(string attributeName, string attributeValue); /// <summary> /// Adds the global attribute, which is valid to some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="attributeName">Attribute name. Max length is 50.</param> /// <param name="attributeValue">Attribute value. Max length is 255.</param> void AddGlobalAttribute(string eventType, string attributeName, string attributeValue); /// <summary> /// Removes the global attribute, which is valid for all events. /// </summary> /// <param name="attributeName">Attribute name.</param> void RemoveGlobalAttribute(string attributeName); /// <summary> /// Removes the global attribute, which is valid to some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="attributeName">Attribute name.</param> void RemoveGlobalAttribute(string eventType, string attributeName); /// <summary> /// Gets the global attribute, which is valid for all events. /// </summary> /// <returns>The global attribute. Return null if attribute doesn't exist.</returns> /// <param name="attributeName">Attribute name.</param> string GetGlobalAttribute(string attributeName); /// <summary> /// Gets the global attribute, which is valid for some specific event type. /// </summary> /// <returns>The global attribute. Return null if attribute doesn't exist. </returns> /// <param name="eventType">Event type.</param> /// <param name="attributeName">Attribute name.</param> string GetGlobalAttribute(string eventType, string attributeName); #endregion #region globalmetric /// <summary> /// Adds the global metric, which is valid for all events. /// </summary> /// <param name="metricName">Metric name. Max length is 50.</param> /// <param name="metricValue">Metric value.</param> void AddGlobalMetric(string metricName, double metricValue); /// <summary> /// Adds the global metric, which is valid for some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="metricName">Metric name. Max length is 50.</param> /// <param name="metricValue">Metric value.</param> void AddGlobalMetric(string eventType, string metricName, double metricValue); /// <summary> /// Removes the global metric, which is valid for all events. /// </summary> /// <param name="metricName">Metric name.</param> void RemoveGlobalMetric(string metricName); /// <summary> /// Removes the global metric, which is valid for some specific event type. /// </summary> /// <param name="eventType">Event type.</param> /// <param name="metricName">Metric name.</param> void RemoveGlobalMetric(string eventType,string metricName); /// <summary> /// Gets the global metric, which is valid for all events. /// </summary> /// <returns>The global metric.Return null if metric doesn't exist.</returns> /// <param name="metricName">Metric name.</param> double? GetGlobalMetric(string metricName); /// <summary> /// Gets the global metric, which is valid for some specific event type. /// </summary> /// <returns>The global metric.Return null if metric doesn't exist.</returns> /// <param name="eventType">Event type.</param> /// <param name="metricName">Metric name.</param> double? GetGlobalMetric(string eventType, string metricName); #endregion } }
185
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections; using System; using Amazon.MobileAnalytics.MobileAnalyticsManager.Internal; using System.Globalization; namespace Amazon.MobileAnalytics.MobileAnalyticsManager { /// <summary> /// Represents purchase event in your application. The event attribute must be set by user. /// <example> /// The example below shows how to use MonetizationEvent /// <code> /// MonetizationEvent monetizationEvent = new MonetizationEvent(); /// /// monetizationEvent.Quantity = 3.0; /// monetizationEvent.ItemPrice = 1.99; /// monetizationEvent.ProductId = "ProductId123"; /// monetizationEvent.ItemPriceFormatted = "$1.99"; /// monetizationEvent.Store = "Apple"; /// monetizationEvent.TransactionId = "TransactionId123"; /// monetizationEvent.Currency = "USD"; /// /// analyticsManager.RecordEvent(monetizationEvent); /// </code> /// </example> /// </summary> public class MonetizationEvent : CustomEvent { // event type private const string PURCHASE_EVENT_NAME = "_monetization.purchase"; // metric name private const string PURCHASE_EVENT_QUANTITY_METRIC = "_quantity"; private const string PURCHASE_EVENT_ITEM_PRICE_METRIC = "_item_price"; // attribute name private const string PURCHASE_EVENT_PRODUCT_ID_ATTR = "_product_id"; private const string PURCHASE_EVENT_ITEM_PRICE_FORMATTED_ATTR = "_item_price_formatted"; private const string PURCHASE_EVENT_STORE_ATTR = "_store"; private const string PURCHASE_EVENT_TRANSACTION_ID_ATTR = "_transaction_id"; private const string PURCHASE_EVENT_CURRENCY_ATTR = "_currency"; /// <summary> /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MonetizationEvent"/> /// </summary> public MonetizationEvent() : base(PURCHASE_EVENT_NAME) { } // metrics /// <summary> /// Sets the quantity. /// </summary> /// <value>The quantity. For example, 1.0 </value> public double? Quantity { get;set; } /// <summary> /// Sets the item price. /// </summary> /// <value>The item price. For example, 3.0 </value> public double? ItemPrice { get;set; } // attributes /// <summary> /// Sets the product identifier. /// </summary> /// <value>The product identifier. For example, ProductId123.</value> public string ProductId { get;set; } /// <summary> /// Sets the item price formatted. /// </summary> /// <value>The item price formatted. For example, $1.99 </value> public string ItemPriceFormatted { get;set; } /// <summary> /// Sets the store. /// </summary> /// <value>The store. For example, AppStore.</value> public string Store { get;set; } /// <summary> /// Sets the transaction identifier. /// </summary> /// <value>The transaction identifier. For example, TransactionId123.</value> public string TransactionId { get;set; } /// <summary> /// Sets the currency. /// </summary> /// <value>The currency.</value> public string Currency { get;set; } /// <summary> /// Converts to mobile analytics model event. <see cref="Amazon.MobileAnalytics.Model.Event"/> /// </summary> /// <returns>The to mobile analytics model event.</returns> /// <param name="session">Session.</param> internal override Amazon.MobileAnalytics.Model.Event ConvertToMobileAnalyticsModelEvent(Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.Session session) { if(Quantity != null) { this.AddMetric(PURCHASE_EVENT_QUANTITY_METRIC,Convert.ToDouble(Quantity, CultureInfo.InvariantCulture)); } if(ItemPrice != null) { this.AddMetric(PURCHASE_EVENT_ITEM_PRICE_METRIC, Convert.ToDouble(ItemPrice, CultureInfo.InvariantCulture)); } if(!string.IsNullOrEmpty(ProductId)) { this.AddAttribute(PURCHASE_EVENT_PRODUCT_ID_ATTR,ProductId); } if(!string.IsNullOrEmpty(ItemPriceFormatted)) { this.AddAttribute(PURCHASE_EVENT_ITEM_PRICE_FORMATTED_ATTR,ItemPriceFormatted); } if(!string.IsNullOrEmpty(Store)) { this.AddAttribute(PURCHASE_EVENT_STORE_ATTR,Store); } if(!string.IsNullOrEmpty(TransactionId)) { this.AddAttribute(PURCHASE_EVENT_TRANSACTION_ID_ATTR,TransactionId); } if(!string.IsNullOrEmpty(Currency)) { this.AddAttribute(PURCHASE_EVENT_CURRENCY_ATTR,Currency); } return base.ConvertToMobileAnalyticsModelEvent(session); } } }
161
aws-mobile-analytics-manager-net
aws
C#
using System; using Amazon.Runtime; using Amazon.Util; using ThirdParty.Json.LitJson; using System.IO; using Amazon.MobileAnalytics.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using System.Net; using System.Globalization; namespace Amazon.MobileAnalytics.Model { public static class EventExtensions { private class DummyResponse : IWebResponseData { long IWebResponseData.ContentLength { get { return 0; } } string IWebResponseData.ContentType { get { return ""; } } HttpStatusCode IWebResponseData.StatusCode { get { return HttpStatusCode.OK; } } bool IWebResponseData.IsSuccessStatusCode { get { return false; } } IHttpResponseBody IWebResponseData.ResponseBody { get { return null; } } bool IWebResponseData.IsHeaderPresent(string headerName) { return false; } string IWebResponseData.GetHeaderValue(string headerName) { return null; } string[] IWebResponseData.GetHeaderNames() { return new string[0]; } } /// <summary> /// Creates a Json string from the Event. Expects Event and Session Timestamps to be in UTC. /// </summary> public static string MarshallToJson(this Event ev) { using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); EventMarshaller.Instance.Marshall(ev, new Runtime.Internal.Transform.JsonMarshallerContext(null, writer)); writer.WriteObjectEnd(); return stringWriter.ToString(); } } /// <summary> /// Creates an Event object from Json. /// </summary> /// <param name="eventValue"> /// The Json string representing the Event. /// </param> public static Event UnmarshallFromJson(this Event ev, String eventValue) { using (MemoryStream responseStream = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(responseStream)) { writer.Write(eventValue); writer.Flush(); responseStream.Position = 0; return EventUnmarshaller.Instance.Unmarshall(new Runtime.Internal.Transform.JsonUnmarshallerContext(responseStream, false, new DummyResponse())); } } } } }
74
aws-mobile-analytics-manager-net
aws
C#
using System.Runtime.InteropServices; [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: System.Security.AllowPartiallyTrustedCallers]
5
aws-mobile-analytics-manager-net
aws
C#
/* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Threading; using System.Collections; using System; using System.IO; using ThirdParty.Json.LitJson; using Amazon.Runtime.Internal.Util; using Amazon.Util; using Amazon.Util.Internal; using Amazon.Runtime.Internal; #if PCL || BCL45 using System.Threading.Tasks; #endif #if PCL using PCLStorage; #endif namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// The class controls session start, pause, resume and stop logic. /// </summary> [System.Security.SecuritySafeCritical] public partial class Session : IDisposable { private Logger _logger = Logger.GetLogger(typeof(Session)); // session info /// <summary> /// Session start Time. /// </summary> public DateTime StartTime { get; set; } /// <summary> /// Session stop time. /// </summary> public DateTime? StopTime { get; set; } /// <summary> /// Session latest resume time. /// </summary> public DateTime PreStartTime { get; set; } /// <summary> /// Session ID. /// </summary> public string SessionId { get; set; } /// <summary> /// Session duration in milliseconds. /// </summary> public long Duration { get; set; } // lock to guard session info private Object _lock = new Object(); internal class SessionStorage { public SessionStorage() { _sessionId = null; _duration = 0; } public DateTime _startTime; public DateTime? _stopTime; public DateTime _preStartTime; public string _sessionId; public long _duration; } private MobileAnalyticsManagerConfig _maConfig; private volatile SessionStorage _sessionStorage = null; private string _appID = null; private string _sessionStorageFileName = "_session_storage.json"; private string _sessionStorageFileFullPath = null; #region public /// <summary> /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.Session"/> /// </summary> /// <param name="appID">Amazon Mobile Analytics App Identifier.</param> /// <param name="maConfig">Mobile Analytics Manager Configuration.</param> [System.Security.SecuritySafeCritical] public Session(string appID, MobileAnalyticsManagerConfig maConfig) { _maConfig = maConfig; _appID = appID; #if BCL _sessionStorageFileFullPath = InternalSDKUtils.DetermineAppLocalStoragePath(appID + _sessionStorageFileName); #elif PCL _sessionStorageFileFullPath = System.IO.Path.Combine(PCLStorage.FileSystem.Current.LocalStorage.Path, appID + _sessionStorageFileName); #endif _logger.InfoFormat("Initialize a new session. The session storage file is {0}.", _sessionStorageFileFullPath); _sessionStorage = new SessionStorage(); } /// <summary> /// Start this session. /// </summary> public void Start() { lock (_lock) { // Read session info from persistent storage, in case app is killed. RetrieveSessionStorage(); // If session storage is valid, restore session and resume session. if (_sessionStorage != null && !string.IsNullOrEmpty(_sessionStorage._sessionId)) { this.StartTime = _sessionStorage._startTime; this.StopTime = _sessionStorage._stopTime; this.SessionId = _sessionStorage._sessionId; this.Duration = _sessionStorage._duration; Resume(); } // Otherwise, create a new session. else { NewSessionHelper(); } } } /// <summary> /// Pause this session. /// </summary> public void Pause() { lock (_lock) { PauseSessionHelper(); SaveSessionStorage(); } } /// <summary> /// Resume this session. /// </summary> public void Resume() { lock (_lock) { if (this.StopTime == null) { //this may sometimes be a valid scenario e.g when the applciation starts _logger.InfoFormat("Call Resume() without calling Pause() first. But this can be valid opertion only when MobileAnalyticsManager instance is created."); return; } DateTime currentTime = AWSSDKUtils.CorrectedUtcNow; if (this.StopTime.Value < currentTime) { // new session if (Convert.ToInt64((currentTime - this.StopTime.Value).TotalMilliseconds) > _maConfig.SessionTimeout * 1000) { StopSessionHelper(); NewSessionHelper(); } // resume old session else { ResumeSessionHelper(); } } else { InvalidOperationException e = new InvalidOperationException(); _logger.Error(e, "Session stop time is earlier than start time !"); } } } #endregion private void NewSessionHelper() { StartTime = AWSSDKUtils.CorrectedUtcNow; PreStartTime = AWSSDKUtils.CorrectedUtcNow; StopTime = null; SessionId = Guid.NewGuid().ToString(); Duration = 0; CustomEvent sessionStartEvent = new CustomEvent(Constants.SESSION_START_EVENT_TYPE); sessionStartEvent.StartTimestamp = StartTime; sessionStartEvent.SessionId = SessionId; MobileAnalyticsManager.GetInstance(_appID).RecordEvent(sessionStartEvent); } private void StopSessionHelper() { DateTime currentTime = AWSSDKUtils.CorrectedUtcNow; // update session info StopTime = currentTime; // record session stop event CustomEvent stopSessionEvent = new CustomEvent(Constants.SESSION_STOP_EVENT_TYPE); stopSessionEvent.StartTimestamp = StartTime; if (StopTime != null) stopSessionEvent.StopTimestamp = StopTime; stopSessionEvent.SessionId = SessionId; stopSessionEvent.Duration = Duration; MobileAnalyticsManager.GetInstance(_appID).RecordEvent(stopSessionEvent); } private void PauseSessionHelper() { DateTime currentTime = AWSSDKUtils.CorrectedUtcNow; // update session info StopTime = currentTime; Duration += Convert.ToInt64((currentTime - PreStartTime).TotalMilliseconds); // record session pause event CustomEvent pauseSessionEvent = new CustomEvent(Constants.SESSION_PAUSE_EVENT_TYPE); pauseSessionEvent.StartTimestamp = StartTime; if (StopTime != null) pauseSessionEvent.StopTimestamp = StopTime; pauseSessionEvent.SessionId = SessionId; pauseSessionEvent.Duration = Duration; MobileAnalyticsManager.GetInstance(_appID).RecordEvent(pauseSessionEvent); } private void ResumeSessionHelper() { DateTime currentTime = AWSSDKUtils.CorrectedUtcNow; // update session info PreStartTime = currentTime; // record session resume event CustomEvent resumeSessionEvent = new CustomEvent(Constants.SESSION_RESUME_EVENT_TYPE); resumeSessionEvent.StartTimestamp = StartTime; if (StopTime != null) resumeSessionEvent.StopTimestamp = StopTime; resumeSessionEvent.SessionId = SessionId; resumeSessionEvent.Duration = Duration; MobileAnalyticsManager.GetInstance(_appID).RecordEvent(resumeSessionEvent); } private void SaveSessionStorage() { _sessionStorage._startTime = StartTime; _sessionStorage._stopTime = StopTime; _sessionStorage._preStartTime = PreStartTime; _sessionStorage._sessionId = SessionId; _sessionStorage._duration = Duration; // store session into file _logger.DebugFormat("Mobile Analytics is about to store session info: {0} ", JsonMapper.ToJson(_sessionStorage)); #if PCL IFolder rootFolder = FileSystem.Current.LocalStorage; IFile file = rootFolder.CreateFileAsync(_sessionStorageFileFullPath, CreationCollisionOption.ReplaceExisting).Result; file.WriteAllTextAsync(JsonMapper.ToJson(_sessionStorage)).Wait(); #elif BCL string directory = Path.GetDirectoryName(_sessionStorageFileFullPath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(_sessionStorageFileFullPath, JsonMapper.ToJson(_sessionStorage)); #endif } private void RetrieveSessionStorage() { string sessionString = null; #if PCL IFolder rootFolder = FileSystem.Current.LocalStorage; if (ExistenceCheckResult.FileExists == rootFolder.CheckExistsAsync(_sessionStorageFileFullPath).Result) { IFile file = rootFolder.GetFileAsync(_sessionStorageFileFullPath).Result; sessionString = file.ReadAllTextAsync().Result; } #elif BCL if (File.Exists(_sessionStorageFileFullPath)) { using (var sessionFile = new System.IO.StreamReader(_sessionStorageFileFullPath)) { sessionString = sessionFile.ReadToEnd(); sessionFile.Close(); } _logger.DebugFormat("Mobile Analytics retrieves session info: {0}", sessionString); } else { _logger.DebugFormat("Mobile Analytics session file does not exist."); } #endif if (!string.IsNullOrEmpty(sessionString)) { _sessionStorage = JsonMapper.ToObject<SessionStorage>(sessionString); } } #region dispose pattern implementation /// <summary> /// Dispose pattern implementation /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose pattern implementation /// </summary> /// <param name="disposing">if disposing</param> protected virtual void Dispose(bool disposing) { } #endregion } }
344
aws-mobile-analytics-manager-net
aws
C#
#if BCL35 /* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections.Generic; using System.Threading; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Amazon Mobile Analytics background runner. /// Background runner periodically calls delivery client to send events to server. /// </summary> public partial class BackgroundRunner { private System.Threading.Thread _thread = null; /// <summary> /// Starts the Mobile Analytics Manager background thread. /// </summary> public void StartWork() { lock (_lock) { if (!IsAlive()) { _thread = new System.Threading.Thread(DoWork); _thread.IsBackground = true; _thread.Start(); } } } private bool IsAlive() { return _thread != null && _thread.ThreadState != ThreadState.Stopped && _thread.ThreadState != ThreadState.Aborted && _thread.ThreadState != ThreadState.AbortRequested; } private void DoWork() { while (!ShouldStop) { try { _logger.InfoFormat("Mobile Analytics Manager is trying to deliver events in background thread."); IDictionary<string, MobileAnalyticsManager> instanceDictionary = MobileAnalyticsManager.CopyOfInstanceDictionary; foreach (string appId in instanceDictionary.Keys) { MobileAnalyticsManager manager = null; try { manager = MobileAnalyticsManager.GetInstance(appId); manager.BackgroundDeliveryClient.AttemptDelivery(); } catch (System.Exception e) { _logger.Error(e, "An exception occurred in Mobile Analytics Delivery Client."); if (null != manager) { MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when deliverying events to Amazon Mobile Analytics.", e, new List<Amazon.MobileAnalytics.Model.Event>()); manager.OnRaiseErrorEvent(eventArgs); } } } Thread.Sleep(BackgroundSubmissionWaitTime * 1000); } catch (System.Exception e) { _logger.Error(e, "An exception occurred in Mobile Analytics Manager."); } } } } } #endif
92
aws-mobile-analytics-manager-net
aws
C#
#if BCL45 /* * Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal { /// <summary> /// Amazon Mobile Analytics background runner. /// Background runner periodically calls delivery client to send events to server. /// </summary> public partial class BackgroundRunner { private int _startFlag = 0; /// <summary> /// Starts the Mobile Analytics Manager background thread. /// </summary> public void StartWork() { // Start background task if it is not started yet. if (0 == Interlocked.CompareExchange(ref _startFlag, 1, 0)) { var task = DoWorkAsync(BackgroundSubmissionWaitTime * 1000); } } private async Task DoWorkAsync(int millisecondsDelay) { while (!ShouldStop) { await Task.Delay(millisecondsDelay).ConfigureAwait(false); if (ShouldStop) break; try { _logger.InfoFormat("Mobile Analytics Manager is trying to deliver events in background thread."); IDictionary<string, MobileAnalyticsManager> instanceDictionary = MobileAnalyticsManager.CopyOfInstanceDictionary; foreach (string appId in instanceDictionary.Keys) { MobileAnalyticsManager manager = null; try { manager = MobileAnalyticsManager.GetInstance(appId); await manager.BackgroundDeliveryClient.AttemptDeliveryAsync().ConfigureAwait(false); } catch (System.Exception e) { _logger.Error(e, "An exception occurred in Mobile Analytics Delivery Client : {0}", e.ToString()); if (null != manager) { MobileAnalyticsErrorEventArgs eventArgs = new MobileAnalyticsErrorEventArgs(this.GetType().Name, "An exception occurred when deliverying events to Amazon Mobile Analytics.", e, new List<Amazon.MobileAnalytics.Model.Event>()); manager.OnRaiseErrorEvent(eventArgs); } } } } catch (System.Exception e) { _logger.Error(e, "An exception occurred in Mobile Analytics Manager : {0}", e.ToString()); } } } } } #endif
85
aws-sam-build-images
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace sam_test_app { public class Functions { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { } /// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The API Gateway response.</returns> public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogLine("Get Request\n"); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "Hello AWS Serverless", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } } }
45
aws-sam-build-images
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; using sam_test_app; namespace test { public class FunctionTest { public FunctionTest() { } [Fact] public void TestGetMethod() { TestLambdaContext context; APIGatewayProxyRequest request; APIGatewayProxyResponse response; Functions functions = new Functions(); request = new APIGatewayProxyRequest(); context = new TestLambdaContext(); response = functions.Get(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("Hello AWS Serverless", response.Body); } } }
39
aws-sam-build-images
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace sam_test_app { public class Functions { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { } /// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The API Gateway response.</returns> public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogLine("Get Request\n"); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "Hello AWS Serverless", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } } }
45
aws-sam-build-images
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; using sam_test_app; namespace test { public class FunctionTest { public FunctionTest() { } [Fact] public void TestGetMethod() { TestLambdaContext context; APIGatewayProxyRequest request; APIGatewayProxyResponse response; Functions functions = new Functions(); request = new APIGatewayProxyRequest(); context = new TestLambdaContext(); response = functions.Get(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("Hello AWS Serverless", response.Body); } } }
39
aws-sam-cli
aws
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace HelloWorld { public class Function { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); return msg.Replace("\n",""); } public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location } }; return new APIGatewayProxyResponse { Body = JsonConvert.SerializeObject(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } }
50
aws-sam-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace HelloWorld.Tests { public class FunctionTest { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var stringTask = client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); var msg = await stringTask; return msg.Replace("\n",""); } [Fact] public async Task TestHelloWorldFunctionHandler() { var request = new APIGatewayProxyRequest(); var context = new TestLambdaContext(); string location = GetCallingIP().Result; Dictionary<string, string> body = new Dictionary<string, string> { { "message", "hello world" }, { "location", location }, }; var expectedResponse = new APIGatewayProxyResponse { Body = JsonConvert.SerializeObject(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; var function = new Function(); var response = await function.FunctionHandler(request, context); Console.WriteLine("Lambda Response: \n" + response.Body); Console.WriteLine("Expected Response: \n" + expectedResponse.Body); Assert.Equal(expectedResponse.Body, response.Body); Assert.Equal(expectedResponse.Headers, response.Headers); Assert.Equal(expectedResponse.StatusCode, response.StatusCode); } } }
58
aws-sam-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace HelloWorld { public class Function { public string FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { return "{'message': 'Hello World'}"; } } public class FirstFunction { public string FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { return "Hello World"; } } public class SecondFunction { public string FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { return "Hello Mars"; } } }
45
aws-sam-cli
aws
C#
using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; using System.Text.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using System.Net.Http.Headers; namespace HelloWorld; public class Function { /// <summary> /// The main entry point for the custom runtime. /// </summary> /// <param name="args"></param> private static async Task Main(string[] args) { Func<APIGatewayHttpApiV2ProxyRequest, ILambdaContext, string> handler = FunctionHandler; await LambdaBootstrapBuilder.Create(handler, new SourceGeneratorLambdaJsonSerializer<MyCustomJsonSerializerContext>()) .Build() .RunAsync(); } public static string FunctionHandler(APIGatewayHttpApiV2ProxyRequest apigProxyEvent, ILambdaContext context) { return "{'message': 'Hello World'}"; } } [JsonSerializable(typeof(APIGatewayHttpApiV2ProxyRequest))] public partial class MyCustomJsonSerializerContext : JsonSerializerContext { }
39
aws-sam-cli
aws
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; using System; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace STS { public class Function { public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var client = new AmazonSecurityTokenServiceClient(); var response = await client.GetCallerIdentityAsync(new GetCallerIdentityRequest {}); string account = response.Account; var body = new Dictionary<string, string> { { "message", "hello world" }, {"account", account} }; return new APIGatewayProxyResponse { Body = JsonConvert.SerializeObject(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } }
42
aws-sam-cli
aws
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; namespace HelloWorld { public class AnotherFunction { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); return msg.Replace("\n",""); } public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary<string, string> { { "message", "hello from another function!!!" }, { "location", location } }; return new APIGatewayProxyResponse { Body = JsonConvert.SerializeObject(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } }
47
aws-sam-cli
aws
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace HelloWorld { public class Function { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); return msg.Replace("\n",""); } public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary<string, string> { { "message", "hello sam accelerate!!!" }, { "location", location } }; return new APIGatewayProxyResponse { Body = JsonConvert.SerializeObject(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } }
50
aws-sam-cli
aws
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; namespace HelloWorld { public class AnotherFunction { private static readonly HttpClient client = new HttpClient(); private static async Task<string> GetCallingIP() { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); return msg.Replace("\n",""); } public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var location = await GetCallingIP(); var body = new Dictionary<string, string> { { "message", "hello from another function!" }, { "extra_message", "hello"}, { "location", location } }; return new APIGatewayProxyResponse { Body = JsonConvert.SerializeObject(body), StatusCode = 200, Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } }; } } }
48