Beispiel #1
0
 /// <summary>
 /// Construtor padrão.
 /// </summary>
 /// <param name="nextMiddlewareInPipelineDelegate"></param>
 /// <param name="logOptions"></param>
 /// <param name="accessor"></param>
 /// <param name="logger"></param>
 public ErrorHandlerMiddleware(RequestDelegate nextMiddlewareInPipelineDelegate, IOptions <LogOptions> logOptions, IHttpContextAccessor accessor, ILogger <ErrorHandlerMiddleware> logger)
 {
     this.nextMiddlewareInPipelineDelegate = nextMiddlewareInPipelineDelegate;
     this.logOptions = logOptions.Value;
     this.accessor   = accessor;
     this.logger     = logger;
 }
Beispiel #2
0
        public override string Query()
        {
            LogOptions.GetLogger().Info("Starting to run mysqldump of database");
            var settings   = BackupSettings.GetInstance();
            var executable = settings.Executable;
            var arguments  = $"-u {settings.User} -p{settings.Password} {settings.Database}";

            LogOptions.GetLogger().Info("Starting dump {executable} {arguments}", executable, arguments);
            try
            {
                var processStartInfo = new ProcessStartInfo
                {
                    FileName               = executable,
                    Arguments              = arguments,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                    CreateNoWindow         = true,
                    UseShellExecute        = false
                };
                var p = Process.Start(processStartInfo);
                var standardOutput = p?.StandardOutput.ReadToEnd();
                p?.WaitForExit();
                return(standardOutput);
            }
            catch (Exception e)
            {
                LogOptions.GetLogger().Fatal(e, "Exception in dump mysql database {message}", e.Message);
                return(string.Empty);
            }
        }
Beispiel #3
0
        protected override void SaveRepositoryConfig(Section section)
        {
            base.SaveRepositoryConfig(section);
            var logOptionsNode = section.GetCreateSection("LogOptions");

            LogOptions.SaveTo(logOptionsNode);
        }
Beispiel #4
0
    public static void SetOptions(LogOptions options)
    {
        _options = options;

        if (options.ExecuteAsync)
        {
            _queue = new AutoQueueExecutor();
        }
        else if (_queue != null)
        {
            _queue.Dispose();
            _queue = null;
        }

        if (options.SaveLog)
        {
            _log = new StringBuilder();
            if (!Directory.Exists("logs"))
            {
                Directory.CreateDirectory("logs");
            }

            if (options.SaveLogTimerMs < LogOptions.MinimumSaveTimer)
            {
                options.SaveLogTimerMs = LogOptions.MinimumSaveTimer;
            }
        }
    }
Beispiel #5
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="logOptions"></param>
 /// <param name="healthCheckOptions"></param>
 /// <param name="memoryCache"></param>
 /// <param name="connectionString"></param>
 public BaseHealthController(IOptions <LogOptions> logOptions, IOptions <HealthCheckOptions> healthCheckOptions, IMemoryCache memoryCache, string connectionString)
 {
     this.memoryCache        = memoryCache ?? throw new ArgumentException("IMemoryCache cannot be null.");
     this.connectionString   = connectionString;
     this.logOptions         = logOptions.Value;
     this.healthCheckOptions = healthCheckOptions.Value;
 }
Beispiel #6
0
        public static void log(string name, string text, LogOptions logO = null)
        {
            if (logO == null)
            {
                logO = DefaultOptions;
            }
            LogEntry loAll = new LogEntry(allkey, text, logO);

            if (logO.WithDate)
            {
                loAll.Text = loAll.Text.Insert(0, DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff") + " " + name + " ");
            }

            LogEntry lo = new LogEntry(name, text, logO);

            if (logO.WithDate)
            {
                lo.Text = lo.Text.Insert(0, DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff") + " ");
            }

            lock (shared) {
                shared.Logs.put(loAll);
                shared.Logs.put(lo);
            }
            if (first)
            {
                first = false;
                init();
            }
        }
Beispiel #7
0
        private static void Write(Severity severity, string message, LogOptions logOptions)
        {
            switch (severity)
            {
            case Severity.Verbose:
                Console.ForegroundColor = ConsoleColor.Gray;
                break;

            case Severity.Info:
                Console.ForegroundColor = ConsoleColor.White;
                break;

            case Severity.Warning:
                Console.ForegroundColor = ConsoleColor.Yellow;
                break;

            case Severity.Error:
                Console.ForegroundColor = ConsoleColor.Magenta;
                break;
            }


            if ((logOptions & LogOptions.NoNewLine) == LogOptions.NoNewLine)
            {
                Console.Write(message);
            }
            else
            {
                Console.WriteLine(message);
            }

            Console.ForegroundColor = ConsoleColor.Gray;
        }
Beispiel #8
0
        protected override void DetachFromRepository(Repository repository)
        {
            base.DetachFromRepository(repository);

            LogSource = null;
            LogOptions.Reset();
        }
Beispiel #9
0
        public static void Log(Exception ex, LogOptions logOption)
        {
            if (ex != null)
            {
                switch (logOption)
                {
                case LogOptions.PromptTheUser:
                    Log(ex.ToString());
                    if (logOption == LogOptions.PromptTheUser)
                    {
                        ErrorTrapper trapper = new ErrorTrapper(ex);
                        trapper.ShowDialog();
                        trapper.Dispose();
                    }
                    break;

                case LogOptions.LogToFile:
                    Log(ex.ToString());
                    break;

                case LogOptions.None:
                    break;
                }
            }
        }
Beispiel #10
0
        public Logger(string logDirectory = null,
            string logFilePrefix = null, 
            string logFileExtension = null, 
            LogLevel logLevel = LogLevel.Error, 
            int messageBufferSize = 32, 
            LogOptions options = LogOptions.LogOnlyToFile, 
            LogRollOptions rollOptions = LogRollOptions.Daily, 
            int rollMaxMegaBytes = 1024,
            bool useUtcTimeStamp = false)
        {
            _logDirectory = logDirectory ?? Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "logs");
            Directory.CreateDirectory(_logDirectory); //will throw if unable - does not throw if already exists
            _logFilePrefix = logFilePrefix ?? LogFilePrefixDefault;
            _logFileExtension = logFileExtension ?? LogFileExtensionDefault;
            _logLevel = logLevel;
            _messageBufferSize = messageBufferSize;
            _rollOptions = rollOptions;
            _rollMaxMegaBytes = rollMaxMegaBytes;
            _useUtcTimeStamp = useUtcTimeStamp;

            LogOptions = options; //setter validates
            if (_messageBufferSize < 1) _messageBufferSize = 1;
            if (_messageBufferSize > 4096) _messageBufferSize = 4096;
            if (_rollOptions == LogRollOptions.Size)
            {
                if (_rollMaxMegaBytes < 1) _rollMaxMegaBytes = 1;
                if (_rollMaxMegaBytes < 4096) _rollMaxMegaBytes = 4096;
            }
        }
Beispiel #11
0
        public Log4netLogger(LogOptions options = null)
        {
            _options = options ?? new LogOptions {
                EnableConsoleLog = true
            };
            var repLogger = LogManager.CreateRepository("jimuLogger");

            //var repDebug = LogManager.CreateRepository("debug");
            //var repInfo = LogManager.CreateRepository("info");
            //var repWarn = LogManager.CreateRepository("warn");
            //var repError = LogManager.CreateRepository("error");
            //UseCodeConfig((Hierarchy)repDebug, "debug");
            //UseCodeConfig((Hierarchy)repInfo, "info");
            //UseCodeConfig((Hierarchy)repError, "error");
            //UseCodeConfig((Hierarchy)repWarn, "warn");
            UseCodeConfig((Hierarchy)repLogger, LogLevel.Debug);
            UseCodeConfig((Hierarchy)repLogger, LogLevel.Info);
            UseCodeConfig((Hierarchy)repLogger, LogLevel.Warn);
            UseCodeConfig((Hierarchy)repLogger, LogLevel.Error);
            _logger = LogManager.GetLogger("jimuLogger", MethodBase.GetCurrentMethod().DeclaringType);
            //_logDebug = LogManager.GetLogger("debug", MethodBase.GetCurrentMethod().DeclaringType);
            //_logInfo = LogManager.GetLogger("info", MethodBase.GetCurrentMethod().DeclaringType);
            //_logError = LogManager.GetLogger("error", MethodBase.GetCurrentMethod().DeclaringType);
            //_logWarn = LogManager.GetLogger("warn", MethodBase.GetCurrentMethod().DeclaringType);
        }
Beispiel #12
0
        public static IEnumerable <string> Log(LogOptions options = default, IEnumerable <string> paths = null)
        {
            const string CommitFormat = "%H %D\n%at\n%ae\n%P\n%B";
            const string Separator    = "%x00%x00";

            yield return("log");

            yield return($"--pretty=format:\"{CommitFormat}{Separator}\"");

            if (options.MaxEntries.HasValue)
            {
                yield return($"-n {options.MaxEntries}");
            }

            if (options.Reverse)
            {
                yield return("--reverse");
            }

            if (options.All)
            {
                yield return("--all");
            }

            if (paths != null)
            {
                yield return("--");

                foreach (var path in paths.Select(QuoteEscape))
                {
                    yield return(path);
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Log method entry
        /// </summary>
        /// <param name="methodName">The name of the method being logged</param>
        /// <param name="options">The log options</param>
        /// <param name="source">The TraceSource that events are written to</param>
        /// <returns>A disposable object or none if logging is disabled</returns>
        public static IDisposable Log(string methodName,
                                      LogOptions options)
        {
            IDisposable logger = null;

            // Check if ExecutionTime logging is requested, and if so log if Verbose
            // logging (or greater) is chosen
            bool shouldCreate = (options & LogOptions.ExecutionTime) == LogOptions.ExecutionTime;

            // If not logging ExecutionTime, see if ActivityTracing is on, and if so
            // log only if Entry or Exit tracing is requested
            if (!shouldCreate)
            {
                shouldCreate = (((options & LogOptions.Entry) == LogOptions.Entry) | ((options & LogOptions.Exit) == LogOptions.Exit));
            }

            // Check if we actually need to log anything
            if (shouldCreate)
            {
                logger = new MethodLogger(methodName, options);
            }

            // Will return null if no method logger was needed - which will
            // effectively be ignored by a using statement.
            return(logger);
        }
Beispiel #14
0
    private static void CreateLogger(string logfile)
    {
        // Enable Serilog debug output to the console
        SelfLog.Enable(Console.Error);

        // Log to console
        // outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
        // Remove lj to quote strings
        LoggerConfiguration loggerConfiguration = new();

        loggerConfiguration.WriteTo.Console(theme: AnsiConsoleTheme.Code, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message}{NewLine}{Exception}");

        // Log to file
        // outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
        // Remove lj to quote strings
        if (!string.IsNullOrEmpty(logfile))
        {
            loggerConfiguration.WriteTo.Async(action => action.File(logfile, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message}{NewLine}{Exception}"));
        }

        // Create static Serilog logger
        Log.Logger = loggerConfiguration.CreateLogger();

        // Set library logger to Serilog logger
        LoggerFactory loggerFactory = new();

        loggerFactory.AddSerilog(Log.Logger);
        LogOptions.CreateLogger(loggerFactory);
    }
Beispiel #15
0
 public TeamCityLog(TextWriter output, LogOptions logOptions, ILogMessageFormatter logMessageFormatter)
     : base(output, output, logOptions, logMessageFormatter)
 {
     Output = output;
     LogOptions = logOptions;
     TeamCityFormatter = new TeamCityFormatter();
 }
        public LoggerMiddlewate(CustomRequestDelegate next, ICustomLogger log, IOptions <LogOptions> options)
        {
            _next = next;
            _log  = log;

            _logOptions = options.Value;
        }
Beispiel #17
0
        private static void writeToLogFile(string text, string filename, LogOptions opts)
        {
            try {
                string logfile      = _folder + filename;
                string createfolder = new FileInfo(logfile).Directory.FullName;
                if (!Directory.Exists(createfolder))
                {
                    Directory.CreateDirectory(createfolder);
                }

                if (File.Exists(logfile))
                {
                    FileInfo finfo = new FileInfo(logfile);
                    if (finfo.Length > opts.LogFileSize)
                    {
                        string oldLog = logfile + ".old";
                        if (File.Exists(oldLog))
                        {
                            File.Delete(oldLog);
                        }
                        File.Move(logfile, oldLog);
                    }
                }
                StreamWriter fout = new StreamWriter(logfile, true);
                fout.Write(text);
                fout.Close();
            } catch { }
        }
Beispiel #18
0
        private static void Write(Severity severity, string message, LogOptions logOptions)
        {
            switch (severity)
            {
                case Severity.Verbose:
                    Console.ForegroundColor = ConsoleColor.Gray;
                    break;
                case Severity.Info:
                    Console.ForegroundColor = ConsoleColor.White;
                    break;
                case Severity.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;
                case Severity.Error:
                    Console.ForegroundColor = ConsoleColor.Magenta;
                    break;
            }

            if ((logOptions & LogOptions.NoNewLine) == LogOptions.NoNewLine)
            {
                Console.Write(message);
            }
            else
            {
                Console.WriteLine(message);
            }

            Console.ForegroundColor = ConsoleColor.Gray;
        }
        public static void ConfigureLog(LogOptions logOptions)
        {
            LoggerConfiguration = new LoggerConfiguration().Enrich.FromLogContext().WriteTo.Console();  //NOSONAR false positive

            if (logOptions.UseLogFile)
            {
                var logFile = logOptions.LogFile != null?string.Format(logOptions.LogFile, DateTime.Today.ToShortDateString().Replace("/", string.Empty)) : DefaultLogFile;

                LoggerConfiguration = LoggerConfiguration.WriteTo.File(GetValidPath(logFile, DefaultLogFile));
            }

            if (!string.IsNullOrEmpty(logOptions.SeqLogServerHost))
            {
                LoggerConfiguration = LoggerConfiguration.WriteTo.Seq(logOptions.SeqLogServerHost);
            }

            if (logOptions.UseSQLiteDb && !string.IsNullOrEmpty(logOptions.SqliteDatabase))
            {
                LoggerConfiguration = LoggerConfiguration.WriteTo.SQLite(GetValidPath(logOptions.SqliteDatabase, DefaultSqliteFile));
            }

            SetLogLevel(logOptions.LogLevel.Default, LoggerConfiguration);

            Log.Logger = LoggerConfiguration.CreateLogger();
        }
Beispiel #20
0
        public Stats(string statsDirectory = null,
            string statsFilePrefix = null,
            string statsFileExtension = null,
            int messageBufferSize = 32,
            int statsBufferSize = 10000,
            LogOptions options = LogOptions.LogOnlyToFile,
            LogRollOptions rollOptions = LogRollOptions.Daily,
            int rollMaxMegaBytes = 1024,
            bool useUtcTimeStamp = false)
        {
            _logDirectory = statsDirectory ?? Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "logs");
            Directory.CreateDirectory(_logDirectory); //will throw if unable - does not throw if already exists
            _logFilePrefix = statsFilePrefix ?? StatFilePrefixDefault;
            _logFileExtension = statsFileExtension ?? StatFileExtensionDefault;
            _messageBufferSize = messageBufferSize;
            _statsBufferSize = statsBufferSize;
            _rollOptions = rollOptions;
            _rollMaxMegaBytes = rollMaxMegaBytes;
            _useUtcTimeStamp = useUtcTimeStamp;

            LogOptions = options;
            if (_messageBufferSize < 1) _messageBufferSize = 1;
            if (_messageBufferSize > 4096) _messageBufferSize = 4096;
            if (_statsBufferSize < 10) _statsBufferSize = 10;
            if (_statsBufferSize > 1000000) _statsBufferSize = 1000000;
            if (_rollOptions == LogRollOptions.Size)
            {
                if (_rollMaxMegaBytes < 1) _rollMaxMegaBytes = 1;
                if (_rollMaxMegaBytes < 4096) _rollMaxMegaBytes = 4096;
            }
        }
Beispiel #21
0
        public void Log(string str, LogOptions option = LogOptions.Verbose)
        {
            if (option == LogOptions.NewLine)
            {
                this.resultBox.AppendText(Environment.NewLine);
                return;
            }

            switch (option)
            {
            case LogOptions.Error:
                resultBox.SelectionColor = Color.Red;
                break;

            case LogOptions.Warning:
                resultBox.SelectionColor = Color.DarkOrange;
                break;

            case LogOptions.Verbose:
                resultBox.SelectionColor = Color.Black;
                break;

            default:
                break;
            }

            this.resultBox.AppendText("[" +
                                      DateTime.Now.ToString("dd/MM - HH:mm:ss") +
                                      (option == LogOptions.Error ? " - ERROR " : string.Empty) + "]: " +
                                      str +
                                      Environment.NewLine);
            this.resultBox.ScrollToCaret();
        }
Beispiel #22
0
        public void LogError(LogOptions option, Exception ex, string additionalInfo)
        {
            try
            {
                SPContext context = SPContext.GetContext(HttpContext.Current);
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPWeb web = new SPSite(context.Web.Url).OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        // implementation details omitted
                        SPList list         = web.Lists["Error-Log"];
                        SPField authorField = list.Fields.GetFieldByInternalName("Author0");
                        SPListItem newItem  = list.AddItem();
                        int maxLength       = 255;
                        string trimmedTitle = ex.Message.Length > maxLength - 1 ? ex.Message.Substring(0, maxLength) : ex.Message;

                        int userId      = context.Web.CurrentUser.ID;
                        string userName = context.Web.CurrentUser.LoginName;
                        SPFieldUserValue authorFieldValue = new SPFieldUserValue(web, userId, userName);

                        newItem["Title"]        = trimmedTitle;
                        newItem["Comment"]      = ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + (ex.InnerException != null ? ex.InnerException.Message : "No Inner Exception") + Environment.NewLine + (ex.InnerException != null ? ex.InnerException.StackTrace : "No Inner Exception Detail" + Environment.NewLine + additionalInfo);
                        newItem["Category"]     = categories[(int)option];
                        newItem[authorField.Id] = authorFieldValue;
                        newItem["IP"]           = HttpContext.Current.Request.UserHostAddress;
                        newItem.Update();

                        web.AllowUnsafeUpdates = false;
                    }
                });
            }
            catch { }
        }
        public StreamOutputListener ConstructorTest(Stream s, LogOptions options)
        {
            StreamOutputListener target = new StreamOutputListener(s, options);

            return(target);
            // TODO: add assertions to method StreamOutputListenerTest.ConstructorTest(Stream, LogOptions)
        }
Beispiel #24
0
 private static void SetupLogAop(ref IServiceCollection services, LogOptions logOptions)
 {
     services.AddTransient <AopControllerAttribute>();
     services.AddTransient <AopExceptionFilterAttribute>();
     services.AddMvc(options => options.Filters.Add(new AopControllerAttribute(logOptions.UseAOPTrace)));
     services.AddMvc(options => options.Filters.Add(new AopExceptionFilterAttribute()));
 }
Beispiel #25
0
        public ErrorHandlingMiddleware(RequestDelegate next, ICustomLogger log, IOptions <LogOptions> logOptions)
        {
            this.next = next;

            this._log = log;

            this._logOptions = logOptions.Value;
        }
 public LogConsole(LogConsoleOptions options = null, LogOptions baseOptions = null) : base(baseOptions)
 {
     options = options ?? new LogConsoleOptions();
     if (options.DebugRect != Rectangle.Empty)
     {
         ConsoleUtils.AdjustConsole(options.DebugRect);
     }
 }
Beispiel #27
0
        public override int Run(string[] remainingArguments)
        {
            var    options = new LogOptions();
            string message = Gitlet.Log(options);

            Console.WriteLine(message);
            return(0);
        }
Beispiel #28
0
        public LoggerMiddleware(RequestDelegate next, ICustomLogger log, IOptions <LogOptions> options)
        {
            this.next = next;

            this._log = log;

            this._options = options.Value;
        }
Beispiel #29
0
        public RepositoryBase()
        {
            _dal.ExecutedEvent += ExecutedEvent;

            _logOptions = ConfigurtaionManager.AppSettings <LogOptions>("logging");

            _logger = new DefaultLogger(_logOptions.Host, _logOptions.Port, _logOptions.Scheme);
        }
 public ConfigurationOptions(AspectWeaverInstance weaverInstance)
 {
     this.onEntryOptions     = weaverInstance.GetConfigurationValue <LogAspectConfiguration, LogOptions>(c => c.OnEntryOptions);
     this.onSuccessOptions   = weaverInstance.GetConfigurationValue <LogAspectConfiguration, LogOptions>(c => c.OnSuccessOptions);
     this.onExceptionOptions = weaverInstance.GetConfigurationValue <LogAspectConfiguration, LogOptions>(c => c.OnExceptionOptions);
     this.onEntryLevel       = weaverInstance.GetConfigurationValue <LogAspectConfiguration, LogLevel>(c => c.OnEntryLevel);
     this.onSuccessLevel     = weaverInstance.GetConfigurationValue <LogAspectConfiguration, LogLevel>(c => c.OnSuccessLevel);
     this.onExceptionLevel   = weaverInstance.GetConfigurationValue <LogAspectConfiguration, LogLevel>(c => c.OnExceptionLevel);
 }
Beispiel #31
0
 private static void SetupLog(ref IServiceCollection services)
 {
     LogOptions = ServiceProvider.GetService <IOptions <LogOptions> >()?.Value;
     if (LogOptions == null)
     {
         return;
     }
     services.SetupLog(LogOptions);
 }
 public ConfigurationOptions( AspectWeaverInstance weaverInstance )
 {
     this.onEntryOptions = weaverInstance.GetConfigurationValue<LogAspectConfiguration, LogOptions>( c => c.OnEntryOptions );
     this.onSuccessOptions = weaverInstance.GetConfigurationValue<LogAspectConfiguration, LogOptions>( c => c.OnSuccessOptions );
     this.onExceptionOptions = weaverInstance.GetConfigurationValue<LogAspectConfiguration, LogOptions>( c => c.OnExceptionOptions );
     this.onEntryLevel = weaverInstance.GetConfigurationValue<LogAspectConfiguration, LogLevel>( c => c.OnEntryLevel );
     this.onSuccessLevel = weaverInstance.GetConfigurationValue<LogAspectConfiguration, LogLevel>( c => c.OnSuccessLevel );
     this.onExceptionLevel = weaverInstance.GetConfigurationValue<LogAspectConfiguration, LogLevel>( c => c.OnExceptionLevel );
 }
Beispiel #33
0
        public static void Initialize(TextWriter _in = null, LogOptions options = null)
        {
            if (_in != null)
            {
                Console.SetOut(_in);
            }

            Host = new Host(options);
        }
Beispiel #34
0
        internal Host(LogOptions options = null)
        {
            if (options != null)
            {
                LogOptions = options;
            }

            LoopTask = BeginTaskLoopAsync();
        }
Beispiel #35
0
        public Stats(string statsDirectory      = null,
                     string statsFilePrefix     = null,
                     string statsFileExtension  = null,
                     int messageBufferSize      = 32,
                     int statsBufferSize        = 10000,
                     LogOptions options         = LogOptions.LogOnlyToFile,
                     LogRollOptions rollOptions = LogRollOptions.Daily,
                     int rollMaxMegaBytes       = 1024,
                     bool useUtcTimeStamp       = false)
        {
            if (options != LogOptions.LogOnlyToConsole && string.IsNullOrWhiteSpace(statsDirectory))
            {
                throw new ArgumentNullException(nameof(statsDirectory));
            }
            if (options != LogOptions.LogOnlyToConsole)
            {
                _logDirectory = statsDirectory;
                Directory.CreateDirectory(_logDirectory); //will throw if unable - does not throw if already exists
                _logFilePrefix    = statsFilePrefix ?? StatFilePrefixDefault;
                _logFileExtension = statsFileExtension ?? StatFileExtensionDefault;
            }
            _messageBufferSize = messageBufferSize;
            _statsBufferSize   = statsBufferSize;
            _rollOptions       = rollOptions;
            _rollMaxMegaBytes  = rollMaxMegaBytes;
            _useUtcTimeStamp   = useUtcTimeStamp;

            LogOptions = options;
            if (_messageBufferSize < 1)
            {
                _messageBufferSize = 1;
            }
            if (_messageBufferSize > 4096)
            {
                _messageBufferSize = 4096;
            }
            if (_statsBufferSize < 10)
            {
                _statsBufferSize = 10;
            }
            if (_statsBufferSize > 1000000)
            {
                _statsBufferSize = 1000000;
            }
            if (_rollOptions == LogRollOptions.Size)
            {
                if (_rollMaxMegaBytes < 1)
                {
                    _rollMaxMegaBytes = 1;
                }
                if (_rollMaxMegaBytes < 4096)
                {
                    _rollMaxMegaBytes = 4096;
                }
            }
        }
Beispiel #36
0
        public void CreateInstanceWithOverridenLogOptions() {
            // arrange
            var logFactoryMock = new Mock<ITaskLogFactory>();
            var factory = new BounceFactory();

            // act
            var logOptions = new LogOptions();
            var bounce = factory.GetBounce(logOptions);

            // assert
            Assert.That(bounce.LogOptions, Is.SameAs(logOptions));
        }
Beispiel #37
0
        /// <summary>
        /// Ctor now private - just called from the static Log method
        /// </summary>
        /// <param name="methodName">The name of the method being logged</param>
        /// <param name="options">The log options</param>        
        private MethodLogger(string methodName, LogOptions options)
        {
            _methodName = methodName;
            _options = options;

            if ((_options & LogOptions.ExecutionTime) == LogOptions.ExecutionTime)
            {
                _sw = new Stopwatch();
                _sw.Start();
            }

            if ((_options & LogOptions.Entry) == LogOptions.Entry)
                Debug.WriteLine("[MethodLogger] Enter method " + methodName);
        }
        public string CreateMessageArguments(LogOptions logOptions, out int[] argumentsIndex)
        {
            StringBuilder formatBuilder = new StringBuilder();

            int arrayLength = this.GetArrayLength(logOptions);
            argumentsIndex = new int[arrayLength];

            formatBuilder.AppendFormat("{0}.{1}", this.targetMethod.DeclaringType, this.targetMethod.Name);
            formatBuilder.Append("(");

            int startParameter = 0;
            if ((logOptions & LogOptions.IncludeThisArgument) != 0 &&
                (this.context.MethodMapping.MethodSignature.CallingConvention & CallingConvention.HasThis) != 0)
            {
                formatBuilder.Append("this = ");
                AppendFormatPlaceholder(0, formatBuilder, this.targetMethod.DeclaringType);
                startParameter = 1;
                argumentsIndex[0] = ThisArgumentPosition;
            }

            bool includeParameterName = (logOptions & LogOptions.IncludeParameterName) != 0;
            bool includeParameterType = (logOptions & LogOptions.IncludeParameterType) != 0;
            bool includeParameterValue = (logOptions & LogOptions.IncludeParameterValue) != 0;

            if (includeParameterName || includeParameterType || includeParameterValue)
            {
                this.WriteMethodArguments(formatBuilder, argumentsIndex, startParameter, includeParameterName, includeParameterType, includeParameterValue);
            }

            formatBuilder.Append(")");

            if (ShouldLogReturnType(logOptions))
            {
                formatBuilder.Append(" : ");
                AppendFormatPlaceholder(argumentsIndex.Length - 1, formatBuilder, this.targetMethod.ReturnParameter.ParameterType);
                argumentsIndex[argumentsIndex.Length - 1] = ReturnParameterPosition;
            }

            return formatBuilder.ToString();
        }
Beispiel #39
0
        /// <summary>
        /// Log method entry 
        /// </summary>
        /// <param name="methodName">The name of the method being logged</param>
        /// <param name="options">The log options</param>
        /// <param name="source">The TraceSource that events are written to</param>
        /// <returns>A disposable object or none if logging is disabled</returns>
        public static IDisposable Log(string methodName,
                                      LogOptions options)
        {
            IDisposable logger = null;

            // Check if ExecutionTime logging is requested, and if so log if Verbose
            // logging (or greater) is chosen
            bool shouldCreate = (options & LogOptions.ExecutionTime) == LogOptions.ExecutionTime;

            // If not logging ExecutionTime, see if ActivityTracing is on, and if so
            // log only if Entry or Exit tracing is requested
            if (!shouldCreate)
                shouldCreate = (((options & LogOptions.Entry) == LogOptions.Entry) | ((options & LogOptions.Exit) == LogOptions.Exit));

            // Check if we actually need to log anything
            if (shouldCreate)
                logger = new MethodLogger(methodName, options);

            // Will return null if no method logger was needed - which will
            // effectively be ignored by a using statement.
            return logger;
        }
Beispiel #40
0
 /// <summary>
 /// Controls the log output. Implemented here primarily to allow dumping the IO from the client utility.
 /// </summary>
 /// <param name="level"> The level of logging. </param>
 public void SetLogLevel(LogOptions level)
 {
     LogLevel = level;
 }
Beispiel #41
0
 public FakeBounce() {
     LogOptions = new LogOptions();
 }
Beispiel #42
0
 public ILog CreateLogForTask(ITask task, TextWriter stdout, TextWriter stderr, LogOptions logOptions)
 {
     if (TeamCityVersion < 6)
         return new TeamCity5Log(stdout, logOptions, new TaskLogMessageFormatter(task));
     return new TeamCityLog(stdout, logOptions, new TaskLogMessageFormatter(task));
 }
Beispiel #43
0
 public TeamCity5Log(TextWriter output, LogOptions logOptions, ILogMessageFormatter logMessageFormatter)
     : base(output, logOptions, logMessageFormatter)
 {
 }
 private bool ShouldLogReturnType(LogOptions logOptions)
 {
     return (logOptions & LogOptions.IncludeReturnValue) != 0 &&
            !IntrinsicTypeSignature.Is(this.context.MethodMapping.MethodSignature.ReturnType, IntrinsicType.Void);
 }
Beispiel #45
0
 public static void Error(string message, LogOptions logOptions = LogOptions.None)
 {
     Write(Severity.Error, message, logOptions);
 }
Beispiel #46
0
 public static void Info(string message, LogOptions logOptions = LogOptions.None)
 {
     Write(Severity.Info, message, logOptions);
 }
Beispiel #47
0
 public ProcessReader(LogOptions logLevel)
 {
     this.logLevel = logLevel;
 }
                private string CreateMessageFormatString(LogOptions logOption, MethodDefDeclaration targetMethod)
                {
                    StringBuilder formatBuilder = new StringBuilder();

                    formatBuilder.AppendFormat("{0}.{1}", targetMethod.DeclaringType, targetMethod.Name);
                    formatBuilder.Append("(");

                    int parameterCount = Context.MethodMapping.MethodSignature.ParameterCount;
                    for (int i = 0; i < parameterCount; i++)
                    {
                        if (i > 0)
                        {
                            formatBuilder.Append(", ");
                        }

                        ITypeSignature parameterType = Context.MethodMapping.MethodSignature.GetParameterType(i);
                        if ((logOption & LogOptions.IncludeParameterType) != 0)
                        {
                            formatBuilder.Append(parameterType.ToString());
                            formatBuilder.Append(' ');
                        }

                        if ((logOption & LogOptions.IncludeParameterName) != 0)
                        {
                            formatBuilder.Append(Context.MethodMapping.MethodMappingInformation.GetParameterName(i));
                            formatBuilder.Append(' ');
                        }

                        if ((logOption & LogOptions.IncludeParameterValue) != 0)
                        {
                            formatBuilder.AppendFormat("= ");

                            if (IntrinsicTypeSignature.Is(parameterType, IntrinsicType.String))
                            {
                                formatBuilder.AppendFormat("\"" + "{{{0}}}" + "\"", i);
                            }
                            else
                            {
                                formatBuilder.AppendFormat("{{{0}}}", i);
                            }
                        }
                    }

                    formatBuilder.Append(")");

                    return formatBuilder.ToString();
                }
Beispiel #49
0
 public static void Warning(string message, LogOptions logOptions = LogOptions.None)
 {
     Write(Severity.Warning, message, logOptions);
 }
        private int GetArrayLength(LogOptions logOptions)
        {
            int result = 0;

            if ((logOptions & LogOptions.IncludeParameterValue) != 0)
            {
                result = this.context.MethodMapping.MethodSignature.ParameterCount;
            }

            if ((logOptions & LogOptions.IncludeThisArgument) != 0 &&
                (this.context.MethodMapping.MethodSignature.CallingConvention & CallingConvention.HasThis) != 0)
            {
                ++result;
            }

            if (ShouldLogReturnType(logOptions))
            {
                ++result;
            }

            return result;
        }
		/// <summary> Sets appropriate (i hope) defaults to all configuration options </summary>
		public static void Configure()
		{
			// DEFAULT OUTPUT FORMATS:
			FORMAT_ASPNET	= LogUtils.PrepareFormatString("{Level,8} - {Message}");
			FORMAT_TRACE	= LogUtils.PrepareFormatString("[{ManagedThreadId:D2}] {Level,8} - {Message}{Location}{Exception}");
			FORMAT_CONSOLE  = LogUtils.PrepareFormatString("[{ManagedThreadId:D2}] {Level,8} - {Message}{Location}{Exception}");
			FORMAT_EVENTLOG = LogUtils.PrepareFormatString("[{ManagedThreadId:D2}] {Level,8} - {Message}{Location}{Exception}");
			FORMAT_LOGFILE	= LogUtils.PrepareFormatString("{EventTime:o} [{ProcessId:D4},{ManagedThreadId:D2}] {Level,8} - {Message}{Location}{Exception}");

			//These filters will apply after the Log.Level filter:
			LEVEL_ASPNET = LogLevels.Verbose;
			LEVEL_TRACE = LogLevels.Verbose;
			LEVEL_CONSOLE = LogLevels.Verbose;
			LEVEL_LOGFILE = LogLevels.Verbose;
			LEVEL_EVENTLOG = LogLevels.Warning;
			
			// INIT DEFAULT LOG LEVELS
			LogOutput = LogOutputs.LogFile;
			LogLevel = LogLevels.Verbose;
			LogOption = LogOptions.Default;
			InnerFormatter = System.Globalization.CultureInfo.InvariantCulture;
			CurrentLogFile = DefaultLogFile;

			FILE_SIZE_THREASHOLD = 10 * 1024 * 1024; // 10mb max log file
			FILE_MAX_HISTORY_SIZE = 10; // Don't keep more than 10

			EventLogName = "Application";
			EventLogSource = ProcessName;

			try 
			{ 
				if( System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Trace.IsEnabled )
					LogOutput |= LogOutputs.AspNetTrace; 
			} catch { }

			if( IsDebugging )
				LogOutput |= LogOutputs.TraceWrite;

			// if debugging or running with asp.net's trace mode, add the file info (we know we aren't in a production environment)
			if( (LogOutput & (LogOutputs.AspNetTrace | LogOutputs.TraceWrite)) != LogOutputs.None )
				LogOption |= LogOptions.LogAddFileInfo;
		}
Beispiel #52
0
 public static void Verbose(string message, LogOptions logOptions = LogOptions.None)
 {
     Write(Severity.Verbose, message, logOptions);
 }
                public Implementation(LoggingAspectTransformationInstance transformationInstance, MethodBodyTransformationContext context)
                    : base(transformationInstance.AspectWeaver.AspectInfrastructureTask, context)
                {
                    this.transformationInstance = transformationInstance;
                    this.backendInstance = this.transformationInstance.parent.backend.CreateInstance(transformationInstance.AspectWeaverInstance);

                    // todo fix configuration
                    this.onEntryOptions = this.transformationInstance.AspectWeaverInstance.GetConfigurationValue<LogAspectConfiguration, LogOptions>(c => c.OnEntryOptions);
                    this.onSuccessOptions = this.transformationInstance.AspectWeaverInstance.GetConfigurationValue<LogAspectConfiguration, LogOptions>(c => c.OnSuccessOptions);
                    this.onExceptionOptions = this.transformationInstance.AspectWeaverInstance.GetConfigurationValue<LogAspectConfiguration, LogOptions>(c => c.OnExceptionOptions);
                }
Beispiel #54
0
 public ITargetBuilderBounce GetBounce(LogOptions logOptions) {
     return new Bounce(logOptions);
 }