public void Trace(
            HttpRequestMessage request,
            string category,
            TraceLevel level,
            Action<TraceRecord> traceAction)
        {
            var trace = new TraceRecord(request, category, level);
            traceAction(trace);

            _traces.Enqueue(trace);

            var context = GlobalHost.ConnectionManager.GetConnectionContext<TracePersistentConnection>();
            context.Groups.Send(
                TracePersistentConnection.Authenticated,
                new
                {
                    trace.RequestId,
                    trace.Request.RequestUri,
                    Status = trace.Status.ToString(),
                    Level = trace.Level.ToString(),
                    trace.Message,
                    trace.Category,
                    TimeTicks = trace.Timestamp.Ticks,
                    trace.Operator,
                    trace.Operation,
                    Exception = trace.Exception == null ? "" : trace.Exception.Message,
                });
        }
 public SystemTraceWriter(IEventGenerator eventGenerator, ScriptSettingsManager settingsManager, TraceLevel level) : base(level)
 {
     _settingsManager = settingsManager;
     _appName = _settingsManager.AzureWebsiteDefaultSubdomain;
     _subscriptionId = Utility.GetSubscriptionId();
     _eventGenerator = eventGenerator;
 }
Example #3
0
		public static void WriteLine(string message, TraceLevel level, params object[] args)
		{

			if (_switch.Level < level)
				return;

			string dateTimeOfEvent = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffff");
			string callingMethod = string.Empty;
			try
			{
				callingMethod = new StackFrame(1).GetMethod().Name;
			}
			catch
			{
				// swallow 
			}


			Trace.WriteLine(string.Format("{0} - {1}: {2}",
				dateTimeOfEvent,
				callingMethod,
				args.Length == 0 ? message : string.Format(message, args)
				));

		}
Example #4
0
        static void DoTrace(TraceMessage message, TraceLevel level)
        {
            if (!message.CorrelationId.HasValue)
            {
                if (Trace.CorrelationManager.ActivityId != Guid.Empty)
                {
                    message.CorrelationId = Trace.CorrelationManager.ActivityId;
                }
            }
            using (var writer = new StringWriter())
            {
                _serializer.Serialize(writer, message);
                // Can't use delegates here as all the Trace methods are [Conditional]
                switch (level)
                {
                    case TraceLevel.Info:
                    default:
                        Trace.TraceInformation(writer.ToString());
                        break;

                    case TraceLevel.Warning:
                        Trace.TraceWarning(writer.ToString());
                        break;

                    case TraceLevel.Error:
                        Trace.TraceError(writer.ToString());
                        break;
                }
            }
        }
Example #5
0
 public static void Trace(TraceLevel level, string format, object param1, object param2, object param3, object param4, object param5)
 {
     if (Utils.TraceListener != null && Utils.TraceListener.ShouldTrace(level))
     {
         TraceCore(level, format, param1, param2, param3, param4, param5);
     }
 }
Example #6
0
 public Tracer(IFileSystem fileSystem, string path, TraceLevel level, IOperationLock traceLock)
 {
     _fileSystem = fileSystem;
     _path = path;
     _level = level;
     _traceLock = traceLock;
 }
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            var record = new TraceRecord(request, category, level);
            traceAction(record);

            var sb = new StringBuilder();
            if (record.Request != null)
            {
                if (record.Request.Method != null)
                {
                    sb.Append(" ");
                    sb.Append(request.Method.ToString());
                }
                if (record.Request.RequestUri != null)
                {
                    sb.Append(" ");
                    sb.Append(record.Request.RequestUri.ToString());
                }
                if (!string.IsNullOrWhiteSpace(record.Category))
                {
                    sb.Append(" ");
                    sb.Append(record.Category);
                }
                sb.Append(" ");
                sb.Append(record.Message);

                if (record.Exception != null)
                {
                    sb.Append(record.Exception.ToString());
                }
            }
            Console.WriteLine(sb.ToString());
        }
Example #8
0
        private static void TestLogging(TraceLevel traceLevel, string messageToLog)
        {
            LoggingSystem loggingSystem = new LoggingSystem("E80.General.TestConsole", false);
            loggingSystem.CurrentLoggingLevel = traceLevel;

            //switch (loggingSystem.CurrentLoggingLevel)
            //{
            //    case TraceLevel.Error:

            //}

            Console.WriteLine("Logging error [IN Windows Event Log and Log File]");
            loggingSystem.LogError("An error occurred: {0}", "Error message text");

            Console.WriteLine();
            Console.WriteLine("Logging Warning [IN Windows Event Log and Log File]");
            loggingSystem.LogWarning("A warning is presented: {0}", "Warning message text");

            Console.WriteLine();
            Console.WriteLine("Logging Info [IN Windows Event Log and Log File]");
            loggingSystem.LogInfo("An info message is presented: {0}", "Info message text");

            Console.WriteLine();
            Console.WriteLine("Logging Verbose [NOT in Windows Event Log - only Log File]");
            loggingSystem.LogVerbose("A verbose message is presented: {0}", "Verbose message text");
        }
Example #9
0
 public static void ConditionalTrace(bool condition, TraceLevel level, string message, params object[] args)
 {
     if (condition)
      {
     Trace(level, message, args);
      }
 }
        /// <summary>
        /// Writes the specified trace level, message and optional exception.
        /// </summary>
        /// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
        /// <param name="message">The trace message.</param>
        /// <param name="ex">The trace exception. This parameter is optional.</param>
        public void Trace(TraceLevel level, string message, Exception ex)
        {
            if (level == TraceLevel.Off)
                return;

            TraceEventCache eventCache = new TraceEventCache();
            TraceEventType traceEventType = GetTraceEventType(level);

            foreach (TraceListener listener in DiagnosticsTrace.Listeners)
            {
                if (!listener.IsThreadSafe)
                {
                    lock (listener)
                    {
                        listener.TraceEvent(eventCache, "Framework.Qlh.Common.Infrastructure.Json", traceEventType, 0, message);
                    }
                }
                else
                {
                    listener.TraceEvent(eventCache, "Framework.Qlh.Common.Infrastructure.Json", traceEventType, 0, message);
                }

                if (DiagnosticsTrace.AutoFlush)
                    listener.Flush();
            }
        }
Example #11
0
 public static void WriteLine(TraceLevel level, string format, object arg1)
 {
     if (TraceListener != null && (level & TraceLevel) > 0)
     {
         TraceListener(format, arg1);
     }
 }
 public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
 {
     foreach (var writer in this.writers)
     {
         writer.Trace(request, category, level, traceAction);
     }
 }
Example #13
0
        private static void WriteLog(TraceLevel level, String messageText)
        {
            try
            {
                EventLogEntryType LogEntryType;
                switch (level)
                {
                    case TraceLevel.Error:
                        LogEntryType = EventLogEntryType.Error;
                        break;
                    default:
                        LogEntryType = EventLogEntryType.Error;
                        break;
                }
                String LogName = "Application";
                if (!EventLog.SourceExists(LogName))
                {
                    EventLog.CreateEventSource(LogName, "BIZ");
                }

                EventLog eventLog = new EventLog(LogName, ".", LogName);//��־���ԵĻ���
                eventLog.WriteEntry(messageText, LogEntryType);
            }
            catch
            {
            }
        }
        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
        {
            if (request != null)
            {
                var traceQueryString = request.GetQueryString("trace"); ;

                bool shouldTrace;
                if (traceQueryString != null &&  Boolean.TryParse(traceQueryString, out shouldTrace)&& shouldTrace)
            {
                    object perRequestTrace;
                    if (!request.Properties.TryGetValue("perRequestTrace", out perRequestTrace))
                    {
                        perRequestTrace = new List<string>();
                        request.Properties["perRequestTrace"] = perRequestTrace;
                    }

                    var record = new TraceRecord(request, category, level);
                    traceAction(record);
                    (perRequestTrace as List<string>).Add(Log(record));
                }
            }

            if (_innerWriter != null)
            {
                _innerWriter.Trace(request, category, level, traceAction);
            }
        }
        protected override void InvokeTextWriter(TraceLevel level, string source, string message, Exception ex)
        {
            if (MapTraceLevel(source, level) <= _traceConfig.ConsoleLevel)
            {
                // For Errors/Warnings we change the Console color
                // for visibility
                var holdColor = Console.ForegroundColor;
                bool changedColor = false;
                switch (level)
                {
                    case TraceLevel.Error:
                        Console.ForegroundColor = ConsoleColor.Red;
                        changedColor = true;
                        break;
                    case TraceLevel.Warning:
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        changedColor = true;
                        break;
                }

                base.InvokeTextWriter(level, source, message, ex);

                if (changedColor)
                {
                    Console.ForegroundColor = holdColor;
                }
            }         
        }
 public static void Validate(TraceLevel value, string parameterValue)
 {
     if (!IsDefined(value))
     {
         throw Error.InvalidEnumArgument(parameterValue, (int)value, typeof(TraceLevel));
     }
 }
 public void Trace(HttpRequestMessage request, string category, TraceLevel level,
     Action<TraceRecord> traceAction)
 {
     var rec = new TraceRecord(request, category, level);
     traceAction(rec);
     WriteTrace(rec);
 }
Example #18
0
 public TraceEntry(TraceLevel level, string message, object values = null)
 {
     Level = level;
     Message = message;
     Values = new DataValueDictionary(values);
     TraceTime = DateTime.UtcNow;
 }
Example #19
0
 protected TraceMessage(string message, TraceLevel level)
 {
     Message = message;
     Level = level;
     Timestamp = DateTime.UtcNow;
     ThreadId = Thread.CurrentThread.ManagedThreadId;
 }
Example #20
0
 public void SetIfNone(TraceLevel level)
 {
     if (!_traceLevel.HasValue)
     {
         _traceLevel = level;
     }
 }
        protected virtual void WriteLine(string context, string message, TraceLevel kind)
        {
            if (kind == TraceLevel.Off)
                return;

            if (kind != TraceLevel.Verbose)
            {
                try {
                    switch (kind)
                    {
                        case TraceLevel.Error:
                            Console.ForegroundColor = ConsoleColor.Red;
                            break;
                        case TraceLevel.Warning:
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            break;
                        case TraceLevel.Info:
                            Console.ForegroundColor = ConsoleColor.Gray;
                            break;
                    }

                    Console.WriteLine("[{0}] {1} {2}", context, kind, message);
                } finally {
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
            }

            this.LogFileWriter.WriteLine("[{0:MM/dd/yy HH:mm:ss}] [{1}] {2}: {3}", DateTime.Now, context, kind, message);
        }
 public static void TracePii(TraceLevel level, string text, object arg0)
 {
     if (tracePiiEnabled)
     {
         instance.Trace(level, text, arg0);
     }
 }
Example #23
0
        public void WriteLine(string message, TraceLevel level = TraceLevel.Info)
        {
            message = this.TracePrefix + message;

              ConsoleColor oldColor = Console.ForegroundColor;
              try {
            switch (level) {
              case TraceLevel.Error:
            Console.ForegroundColor = PluginTrace.ConsoleErrorColor;
            TShock.Log.Error(message);
            break;
              case TraceLevel.Warning:
            Console.ForegroundColor = PluginTrace.ConsoleWarningColor;
            TShock.Log.Warn(message);
            break;
              default:
            TShock.Log.Info(message);
            break;
            }

            Console.WriteLine(message);
              } finally {
            Console.ForegroundColor = oldColor;
              }
        }
Example #24
0
        public void Log(TraceLevel level, string message, Exception ex)
        {
            switch (level)
            {
                case TraceLevel.Fatal:
                    Logger.Fatal(message, ex);
                    break;

                case TraceLevel.Error:
                    Logger.Error(message, ex);
                    break;

                case TraceLevel.Warn:
                    Logger.Warn(message, ex);
                    break;

                case TraceLevel.Info:
                    Logger.Info(message, ex);
                    break;

                case TraceLevel.Debug:
                    Logger.Debug(message, ex);
                    break;
            }
        }
Example #25
0
 public LogData(DateTime dateTime, TraceLevel level, string message, string category)
 {
     Time = dateTime;
     Level = level;
     Message = message;
     Category = category;
 }
        public FileTraceWriter(string logFilePath, TraceLevel level) : base(level)
        {
            _logFilePath = logFilePath;
            _instanceId = GetInstanceId();

            _logDirectory = new DirectoryInfo(logFilePath);
            if (!_logDirectory.Exists)
            {
                _logDirectory.Create();
            }
            else
            {
                // query for all existing log files for this instance
                // sorted by date, and get the last log file written to (or null)
                var files = GetLogFiles(_logDirectory);
                _currentLogFileInfo = files.FirstOrDefault();
            }

            if (_currentLogFileInfo == null)
            {
                SetNewLogFile();
            }

            // start a timer to flush accumulated logs in batches
            _flushTimer = new Timer
            {
                AutoReset = true,
                Interval = LogFlushIntervalMs
            };
            _flushTimer.Elapsed += OnFlushLogs;
            _flushTimer.Start();
        }
        /// <summary>
        /// Writes the specified line to the trace log, processing the entry to
        /// determine the trace level.
        /// </summary>
        /// <param name="message">The message to be written.</param>
        public override void WriteLine( string message )
        {
            if( string.IsNullOrEmpty( message ) )
                return;

            if( this.fs == null )
                return;

            if( message.EndsWith( "Information: 0 : " ) )
            {
                this.type = TraceLevel.Info;
                return;
            }
            else if( message.EndsWith( "Warning: 0 : " ) )
            {
                this.type = TraceLevel.Warning;
                return;
            }
            else if( message.EndsWith( "Error: 0 : " ) )
            {
                this.type = TraceLevel.Error;
                return;
            }

            lock( this.fs.Logs )
            {
                LogItem log = new LogItem( this.type, message );
                this.fs.Logs.Add( log );
            }
        }
 public static void TracePii(TraceLevel level, string text)
 {
     if (tracePiiEnabled)
     {
         instance.Trace(level, text);
     }
 }
Example #29
0
 public static void Trace(TraceLevel level, string message)
 {
     if (Utils.TraceListener != null && Utils.TraceListener.ShouldTrace(level))
     {
         Utils.TraceListener.Trace(level, message);
     }
 }
        /// <summary>
        /// Writes the specified trace level, message and optional exception.
        /// </summary>
        /// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
        /// <param name="message">The trace message.</param>
        /// <param name="ex">The trace exception. This parameter is optional.</param>
        public void Trace(TraceLevel level, string message, Exception ex)
        {
            if (level == TraceLevel.Off)
            {
                return;
            }

            TraceEventCache eventCache = new TraceEventCache();
            TraceEventType traceEventType = GetTraceEventType(level);

            foreach (TraceListener listener in DiagnosticsTrace.Listeners)
            {
                if (!listener.IsThreadSafe)
                {
                    lock (listener)
                    {
                        listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
                    }
                }
                else
                {
                    listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message);
                }

                if (DiagnosticsTrace.AutoFlush)
                {
                    listener.Flush();
                }
            }
        }
Example #31
0
 private static void WriteLog(object message, Exception t, TraceLevel severity)
 {
     WriteLog(message, t, severity, null);
 }
Example #32
0
        /// <summary>
        /// Helper method that does the core instantiation & initialization of face tracking engine
        /// </summary>
        /// <param name="newColorCameraConfig">Color camera configuration</param>
        /// <param name="newDepthCameraConfig">Depth camera configuration</param>
        /// <param name="colorImagePtr">Allows face tracking engine to read color image from native memory pointer.
        /// If set to IntPtr.Zero, image data needs to be provided for tracking to this instance. </param>
        /// <param name="depthImagePtr">Allows face tracking engine to read depth image from native memory pointer.
        /// If set to IntPtr.Zero, image data needs to be provided for tracking to this instance.</param>
        /// <param name="newRegisterDepthToColorDelegate">Callback which maps of depth to color pixels</param>
        private void Initialize(
            CameraConfig newColorCameraConfig,
            CameraConfig newDepthCameraConfig,
            IntPtr colorImagePtr,
            IntPtr depthImagePtr,
            FaceTrackingRegisterDepthToColor newRegisterDepthToColorDelegate)
        {
            if (newColorCameraConfig == null)
            {
                throw new ArgumentNullException("newColorCameraConfig");
            }

            if (newDepthCameraConfig == null)
            {
                throw new ArgumentNullException("newDepthCameraConfig");
            }

            if (newRegisterDepthToColorDelegate == null)
            {
                throw new ArgumentNullException("newRegisterDepthToColorDelegate");
            }

            // initialize perf counters
            this.totalTracks = 0;
            this.trackStopwatch.Reset();

            // get configuration & trace settings
            this.traceLevel = new TraceSwitch(FaceTrackTraceSwitchName, FaceTrackTraceSwitchName).Level;

            this.videoCameraConfig            = newColorCameraConfig;
            this.depthCameraConfig            = newDepthCameraConfig;
            this.registerDepthToColorDelegate = newRegisterDepthToColorDelegate;

            this.faceTrackerInteropPtr = NativeMethods.FTCreateFaceTracker(IntPtr.Zero);
            if (this.faceTrackerInteropPtr == null)
            {
                throw new InsufficientMemoryException("Cannot create face tracker.");
            }

            IntPtr funcPtr = Marshal.GetFunctionPointerForDelegate(this.registerDepthToColorDelegate);

            if (funcPtr == IntPtr.Zero)
            {
                throw new InsufficientMemoryException("Cannot setup callback for retrieving color to depth pixel mapping");
            }

            int hr = this.faceTrackerInteropPtr.Initialize(this.videoCameraConfig, this.depthCameraConfig, funcPtr, null);

            if (hr != 0)
            {
                throw new InvalidOperationException(
                          string.Format(CultureInfo.CurrentCulture, "Failed to initialize face tracker - Error code from native=0x{0:X}", hr));
            }

            this.frame = this.CreateResult(out hr);
            if (this.frame == null || hr != 0)
            {
                throw new InvalidOperationException(
                          string.Format(CultureInfo.CurrentCulture, "Failed to create face tracking result. Error code from native=0x{0:X}", hr));
            }

            this.colorFaceTrackingImage = new Image();
            if (colorImagePtr == IntPtr.Zero)
            {
                this.colorFaceTrackingImage.Allocate(
                    this.videoCameraConfig.Width, this.videoCameraConfig.Height, this.videoCameraConfig.ImageFormat);
            }
            else
            {
                this.colorFaceTrackingImage.Attach(
                    this.videoCameraConfig.Width,
                    this.videoCameraConfig.Height,
                    colorImagePtr,
                    this.videoCameraConfig.ImageFormat,
                    this.videoCameraConfig.Stride);
            }

            this.depthFaceTrackingImage = new Image();
            if (depthImagePtr == IntPtr.Zero)
            {
                this.depthFaceTrackingImage.Allocate(
                    this.depthCameraConfig.Width, this.depthCameraConfig.Height, this.depthCameraConfig.ImageFormat);
            }
            else
            {
                this.depthFaceTrackingImage.Attach(
                    this.depthCameraConfig.Width,
                    this.depthCameraConfig.Height,
                    depthImagePtr,
                    this.depthCameraConfig.ImageFormat,
                    this.depthCameraConfig.Stride);
            }
        }
            private static void WriteTraceRecursive(
                TextWriter writer,
                ITrace trace,
                TraceLevel level,
                AsciiTreeIndents asciiTreeIndents,
                bool isLastChild)
            {
                ITrace         parent      = trace.Parent;
                Stack <string> indentStack = new Stack <string>();

                while (parent != null)
                {
                    bool parentIsLastChild = (parent.Parent == null) || parent.Equals(parent.Parent.Children.Last());
                    if (parentIsLastChild)
                    {
                        indentStack.Push(asciiTreeIndents.Blank);
                    }
                    else
                    {
                        indentStack.Push(asciiTreeIndents.Parent);
                    }

                    parent = parent.Parent;
                }

                WriteIndents(writer, indentStack, asciiTreeIndents, isLastChild);

                writer.Write(trace.Name);
                writer.Write('(');
                writer.Write(trace.Id);
                writer.Write(')');
                writer.Write(space);

                writer.Write(trace.Component);
                writer.Write('-');
                writer.Write("Component");
                writer.Write(space);

                writer.Write(trace.CallerInfo.MemberName);

                writer.Write('@');
                writer.Write(GetFileNameFromPath(trace.CallerInfo.FilePath));
                writer.Write(':');
                writer.Write(trace.CallerInfo.LineNumber);
                writer.Write(space);

                writer.Write(trace.StartTime.ToString("hh:mm:ss:fff", CultureInfo.InvariantCulture));
                writer.Write(space);

                writer.Write(trace.Duration.TotalMilliseconds.ToString("0.00"));
                writer.Write(" milliseconds");
                writer.Write(space);

                writer.WriteLine();

                if (trace.Data.Count > 0)
                {
                    bool isLeaf = trace.Children.Count == 0;

                    WriteInfoIndents(writer, indentStack, asciiTreeIndents, isLastChild: isLastChild, isLeaf: isLeaf);
                    writer.WriteLine('(');

                    foreach (KeyValuePair <string, object> kvp in trace.Data)
                    {
                        string key   = kvp.Key;
                        object value = kvp.Value;

                        WriteInfoIndents(writer, indentStack, asciiTreeIndents, isLastChild: isLastChild, isLeaf: isLeaf);
                        writer.Write(asciiTreeIndents.Blank);
                        writer.Write('[');
                        writer.Write(key);
                        writer.Write(']');
                        writer.WriteLine();

                        string traceDatumToString;
                        if (value is TraceDatum traceDatum)
                        {
                            TraceDatumTextWriter traceDatumTextWriter = new TraceDatumTextWriter();
                            traceDatum.Accept(traceDatumTextWriter);

                            traceDatumToString = traceDatumTextWriter.ToString();
                        }
                        else
                        {
                            traceDatumToString = value.ToString();
                        }

                        string[] infoLines = traceDatumToString
                                             .TrimEnd(newLineCharacters)
                                             .Split(newLines, StringSplitOptions.None);
                        foreach (string infoLine in infoLines)
                        {
                            WriteInfoIndents(writer, indentStack, asciiTreeIndents, isLastChild: isLastChild, isLeaf: isLeaf);
                            writer.Write(asciiTreeIndents.Blank);
                            writer.WriteLine(infoLine);
                        }
                    }

                    WriteInfoIndents(writer, indentStack, asciiTreeIndents, isLastChild: isLastChild, isLeaf: isLeaf);
                    writer.WriteLine(')');
                }

                for (int i = 0; i < trace.Children.Count - 1; i++)
                {
                    ITrace child = trace.Children[i];
                    WriteTraceRecursive(writer, child, level, asciiTreeIndents, isLastChild: false);
                }

                if (trace.Children.Count != 0)
                {
                    ITrace child = trace.Children[trace.Children.Count - 1];
                    WriteTraceRecursive(writer, child, level, asciiTreeIndents, isLastChild: true);
                }
            }
Example #34
0
 public SystemTraceWriter(TraceLevel level) : this(new EventGenerator(), level)
 {
 }
 public override void Log(string message, TraceLevel level = TraceLevel.Info)
 {
 }
 internal void Log(TraceLevel level, string eventName, params object[] args)
 {
     _log?.Log(level, eventName, args);
 }
Example #37
0
        // key goal is to create background tracer that is independent of request.
        public static async Task <bool> PerformBackgroundDeployment(
            DeploymentInfoBase deployInfo,
            IEnvironment environment,
            IDeploymentSettingsManager settings,
            TraceLevel traceLevel,
            Uri uri,
            bool waitForTempDeploymentCreation)
        {
            var tracer       = traceLevel <= TraceLevel.Off ? NullTracer.Instance : new CascadeTracer(new XmlTracer(environment.TracePath, traceLevel), new ETWTracer(environment.RequestId, "POST"));
            var traceFactory = new TracerFactory(() => tracer);

            var backgroundTrace = tracer.Step(XmlTracer.BackgroundTrace, new Dictionary <string, string>
            {
                { "url", uri.AbsolutePath },
                { "method", "POST" }
            });

            // For waiting on creation of temp deployment
            var tempDeploymentCreatedTcs = new TaskCompletionSource <object>();

            // For determining whether or not we failed to create the deployment due to lock contention.
            // Needed for deployments where deferred deployment is not allowed. Will be set to false if
            // lock contention occurs and AllowDeferredDeployment is false, otherwise true.
            var deploymentWillOccurTcs = new TaskCompletionSource <bool>();

            // This task will be let out of scope intentionally
            var deploymentTask = Task.Run(() =>
            {
                try
                {
                    // lock related
                    string lockPath           = Path.Combine(environment.SiteRootPath, Constants.LockPath);
                    string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile);
                    string statusLockPath     = Path.Combine(lockPath, Constants.StatusLockFile);
                    string hooksLockPath      = Path.Combine(lockPath, Constants.HooksLockFile);
                    var statusLock            = new LockFile(statusLockPath, traceFactory);
                    var hooksLock             = new LockFile(hooksLockPath, traceFactory);
                    var deploymentLock        = new DeploymentLockFile(deploymentLockPath, traceFactory);

                    var analytics = new Analytics(settings, new ServerConfiguration(), traceFactory);
                    var deploymentStatusManager = new DeploymentStatusManager(environment, analytics, statusLock);
                    var siteBuilderFactory      = new SiteBuilderFactory(new BuildPropertyProvider(), environment);
                    var webHooksManager         = new WebHooksManager(tracer, environment, hooksLock);
                    var deploymentManager       = new DeploymentManager(siteBuilderFactory, environment, traceFactory, analytics, settings, deploymentStatusManager, deploymentLock, NullLogger.Instance, webHooksManager);
                    var fetchDeploymentManager  = new FetchDeploymentManager(settings, environment, tracer, deploymentLock, deploymentManager, deploymentStatusManager);

                    IDisposable tempDeployment = null;

                    try
                    {
                        // Perform deployment
                        deploymentLock.LockOperation(() =>
                        {
                            deploymentWillOccurTcs.TrySetResult(true);

                            ChangeSet tempChangeSet = null;
                            if (waitForTempDeploymentCreation)
                            {
                                // create temporary deployment before the actual deployment item started
                                // this allows portal ui to readily display on-going deployment (not having to wait for fetch to complete).
                                // in addition, it captures any failure that may occur before the actual deployment item started
                                tempDeployment = deploymentManager.CreateTemporaryDeployment(
                                    Resources.ReceivingChanges,
                                    out tempChangeSet,
                                    deployInfo.TargetChangeset,
                                    deployInfo.Deployer);

                                tempDeploymentCreatedTcs.TrySetResult(null);
                            }

                            fetchDeploymentManager.PerformDeployment(deployInfo, tempDeployment, tempChangeSet).Wait();
                        }, "Performing continuous deployment", TimeSpan.Zero);
                    }
                    catch (LockOperationException)
                    {
                        if (tempDeployment != null)
                        {
                            tempDeployment.Dispose();
                        }

                        if (deployInfo.AllowDeferredDeployment)
                        {
                            deploymentWillOccurTcs.TrySetResult(true);

                            using (tracer.Step("Update pending deployment marker file"))
                            {
                                // REVIEW: This makes the assumption that the repository url is the same.
                                // If it isn't the result would be buggy either way.
                                FileSystemHelpers.SetLastWriteTimeUtc(fetchDeploymentManager._markerFilePath, DateTime.UtcNow);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    tracer.TraceError(ex);
                }
                finally
                {
                    // Will no-op if already set
                    deploymentWillOccurTcs.TrySetResult(false);
                    backgroundTrace.Dispose();
                }
            });

#pragma warning disable 4014
            // Run on BG task (Task.Run) to avoid ASP.NET Request thread terminated with request completion and
            // it doesn't get chance to clean up the pending marker.
            Task.Run(() => PostDeploymentHelper.TrackPendingOperation(deploymentTask, TimeSpan.Zero));
#pragma warning restore 4014

            // When the frontend/ARM calls /deploy with isAsync=true, it starts polling
            // the deployment status immediately, so it's important that the temp deployment
            // is created before we return.
            if (waitForTempDeploymentCreation)
            {
                // deploymentTask may return withoout creating the temp deployment (lock contention,
                // other exception), in which case just continue.
                await Task.WhenAny(tempDeploymentCreatedTcs.Task, deploymentTask);
            }

            // If deferred deployment is not permitted, we need to know whether or not the deployment was
            // successfully requested. Otherwise, to preserve existing behavior, we assume it was.
            if (!deployInfo.AllowDeferredDeployment)
            {
                return(await deploymentWillOccurTcs.Task);
            }
            else
            {
                return(true);
            }
        }
Example #38
0
        //// Manages the archive files (*_01, *_02, etc.).
        //// Parameter renamedFile is what the old output file was renamed
        //// to if it existed (with extension .tempname).
        //// It must become the _01 file.
        //// if renamedFile is null, the old output file wasn't replaced (did't
        //// exist or was opened in append mode), and no renaming is necessary,
        //// but we still delete files with numbers higher than Archives.
        //private void ManageArchives(string renamedFile)
        //{
        //    string bareFilePath = Path.Combine(Directory, _logFileName);
        //    int highestNumKept = (renamedFile == null) ? (int)Archives : (int)Archives - 1;

        //    // This gets the archived files in reverse order.
        //    string[] files = EnumOldFiles("_??.txt");

        //    if (files != null)
        //    {
        //        foreach (string oldFile in files)
        //        {
        //            // Extract the archive number that comes after "bareFileName_".
        //            // The number must be two numeric chars or it's not one of our files.
        //            string plain = Path.GetFileNameWithoutExtension(oldFile);
        //            string numPart = plain.Substring(_logFileName.Length + 1);

        //            if (numPart.Length == 2)
        //            {
        //                int num;

        //                if (int.TryParse(numPart, out num) && num > 0)
        //                {
        //                    if (num > highestNumKept)
        //                    {
        //                        // The archive number is more than the user wants to keep, so delete it.
        //                        try
        //                        {
        //                            File.Delete(oldFile);
        //                        }
        //                        catch (Exception ex)
        //                        {
        //                            string msg = string.Format("An exception occurred while deleting the old log file\n{0}\n\n{1}", oldFile, ex);
        //                            Logger.EventLogging.Log(msg, Logger.EventLogging.ExceptionInArchive);
        //                        }
        //                    }
        //                    else if (renamedFile != null)
        //                    {
        //                        // Rename (increment the file's archive number by 1).
        //                        TryRename(oldFile, bareFilePath, num + 1);
        //                    }
        //                }
        //            }
        //        }

        //        // Finally, rename the most recent log file, if it exists.
        //        if (renamedFile != null)
        //        {
        //            TryRename(renamedFile, bareFilePath, 1);
        //        }
        //    }
        //}

        // Logs a message to the text file, possibly wrapping or starting a new file.
        internal void LogMsg(Logger logger, ThreadData threadData, TraceLevel msgLevel, string msg)
        {
            lock (_fileLocker)
            {
                try
                {
                    if (IsOpen)
                    {
                        DateTime utcNow   = DateTime.UtcNow;
                        DateTime localNow = utcNow.ToLocalTime();

                        //System.Diagnostics.Debug.Print("Position = " + BaseStream.Position);

                        if (BaseStream.Position >= _maxFilePosition)
                        {
                            // The previously written line reached the max file size, so apply the FullFilePolicy.

                            switch (FullFilePolicy)
                            {
                            case FullFilePolicy.Close:
                                // This should really never happen because we check for this condition
                                // immediately after writing the line.
                                Close();
                                break;

                            case FullFilePolicy.Roll:
                                RestartFile();
                                WriteLine(logger, threadData, msgLevel, localNow, msg);
                                break;

                            case FullFilePolicy.Wrap:
                                if (CircularStarted)
                                {
                                    string wrapMsg = String.Format("TracerX: Returning (wrapping) to file position {0} for next log message.", _positionOfCircularPart);
                                    WriteLine(logger, threadData, msgLevel, localNow, wrapMsg);
                                    BaseStream.Position = _positionOfCircularPart;

                                    if (!_wrapped)
                                    {
                                        _wrapped = true;
                                        Logger.EventLogging.Log("The text file wrapped for the first time: " + FullPath, Logger.EventLogging.FirstWrap);
                                    }

                                    WriteLine(logger, threadData, msgLevel, localNow, msg);
                                }
                                else
                                {
                                    // Since the circular didn't start, there's no where to wrap to.  Log an error and close the file.

                                    string closeMsg = string.Format("TracerX: File is closing (not wrapping) because FullFilePolicy = Wrap and the file reached maximum size ({0}) before circular logging started.  ", _maxFilePosition);
                                    Logger.EventLogging.Log(closeMsg + "\n" + FullPath, Logger.EventLogging.MaxFileSizeReached);

                                    WriteLine(logger, threadData, msgLevel, localNow, closeMsg);

                                    closeMsg = string.Format("MaxSizeMb = {0}, AppendIfSmallerThanMb = {1}, UseKbForSize = {2}", MaxSizeMb, AppendIfSmallerThanMb, UseKbForSize);
                                    WriteLine(logger, threadData, msgLevel, localNow, closeMsg);

                                    Close();
                                }

                                break;
                            }
                        }
                        else
                        {
                            // Possibly start the circular log based on the current time and/or file size.
                            // Note that _circularStartTime is UTC.

                            if (FullFilePolicy == FullFilePolicy.Wrap && !CircularStarted &&
                                (utcNow >= _circularStartTime ||
                                 (CircularStartSizeKb > 0 && (BaseStream.Position - _openSize) >= CircularStartSizeKb << 10)))
                            {
                                // Start the circular log, which basically means setting _positionOfCircularPart so we know where
                                // to set the file position when it's time to wrap in the future.

                                WriteLine(logger, threadData, msgLevel, localNow, "TracerX: Last line before circular log starts.");
                                _positionOfCircularPart = BaseStream.Position;
                                WriteLine(logger, threadData, msgLevel, localNow, "TracerX: First line in circular portion of log (never wrapped if you see this whole line).");

                                if (BaseStream.Position >= _maxFilePosition)
                                {
                                    // The messages we just wrote exceeded the max file size, which means there really wasn't enough room to do circular logging.
                                    Logger.EventLogging.Log("Circular logging would have started, but there was not enough room left in the file: " + FullPath, Logger.EventLogging.TooLateForCircular);
                                    WriteLine(logger, threadData, msgLevel, localNow, "TracerX: Max file size exceeded.  FullFilePolicy = Wrap, but insufficient space to start the circular log.  Closing file (not rolling).");

                                    Close();
                                }
                                else
                                {
                                    string eventMsg = String.Format("Circular logging has started for text file '{0}' with {1:N0} bytes remaining.", FullPath, _maxFilePosition - CurrentPosition);
                                    Logger.EventLogging.Log(eventMsg, Logger.EventLogging.CircularLogStarted);
                                }
                            }

                            WriteLine(logger, threadData, msgLevel, localNow, msg);

                            if (FullFilePolicy == FullFilePolicy.Close && IsOpen && BaseStream.Position >= _maxFilePosition)
                            {
                                string closeMsg = string.Format("TracerX: Closing file (not rolling or wrapping) because the maximum size was reached and FullFilePolicy = Close, MaxSizeMb = {0}, AppendIfSmallerThanMb = {1}, UseKbForSize = {2}", MaxSizeMb, AppendIfSmallerThanMb, UseKbForSize);
                                WriteLine(logger, threadData, msgLevel, localNow, closeMsg);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Give up!  close the log file.
                    Logger.EventLogging.Log("An exception was thrown while logging to the text file: " + ex.ToString(), Logger.EventLogging.ExceptionInLogger);
                    Close();
                }
            }
        }
 public abstract void Log(string message, TraceLevel level = TraceLevel.Info);
 public abstract bool IsEnabledFor(TraceLevel level);
 public virtual void Log(object value, TraceLevel level = TraceLevel.Info)
 => Log(value.ToString(), level);
 public override bool IsEnabledFor(TraceLevel level)
 => false;
Example #43
0
 public static void Log(TraceLevel level, object value, [CallerMemberName] string methodName = null) => Logger?.Log(level, value, methodName);
        /// <summary>
        /// Creates a new parser settings instance with cusomizable setting values.
        /// </summary>
        /// <param name="skipUnknown">Flag if unknown tags should be ignored</param>
        /// <param name="skipOverTags">Any known but unusable tags that should be skipped completely (including any of their inner content)</param>
        /// <param name="escapeEntites">All the escaped entities mapping HTML entities (e.g. &amp;) to the character equivalent (e.g. &)</param>
        private HTMLParserSettings(bool skipUnknown, bool skipCssClasses, bool skipStyles, bool skipProcessingInstructions, bool skipComments, bool skipDocType, bool skipCData, TraceLevel loglevel, PDFTraceLog log, IList <string> skipOverTags, IDictionary <string, char> escapeEntites)
        {
            if (null == escapeEntites)
            {
                throw new ArgumentNullException("escapeEntities");
            }
            if (null == skipOverTags)
            {
                throw new ArgumentNullException("skipOverTags");
            }

            this.SkipUnknownTags            = skipUnknown;
            this.SkipOverTags               = skipOverTags;
            this.SkipComments               = skipComments;
            this.SkipDocType                = skipDocType;
            this.SkipCData                  = skipCData;
            this.SkipCssClasses             = skipCssClasses;
            this.SkipStyles                 = skipStyles;
            this.SkipProcessingInstructions = skipProcessingInstructions;
            this.HTMLEntityMappings         = escapeEntites;
            this.LogLevel = loglevel;
            this.TraceLog = log;
        }
 public void Trace(TraceLevel level, string message, Exception ex)
 {
     Console.WriteLine(message);
 }
Example #46
0
 protected void TraceOnPrimaryHost(string message, TraceLevel level)
 {
     TraceWriter.Trace(message, level, PrimaryHostTraceProperties);
 }
Example #47
0
        public const int MaxOnScreenLogLength = 1024 * 1024; // 1mb of characters

        public static void AddToLogView(TraceLevel traceLevel, string prefix, string message)
        {
            _loggerPump.Enqueue(new LogMessage(traceLevel, prefix, message));
        }
Example #48
0
 public static void ChangeLogLevel(TraceLevel maximumLogLevel)
 {
     _traceSource.Switch = new SourceSwitch("MySourceSwitch", ConvertTraceLevelToSourceLevels(maximumLogLevel).ToString());
 }
Example #49
0
 public BusinessException(string message, Exception inner, TraceLevel traceLevel) : base(message, inner)
 {
     TraceLevel = traceLevel;
 }
Example #50
0
 public TestTraceWriter(TraceLevel level) : base(level)
 {
     _level = level;
 }
Example #51
0
 public BusinessException(TraceLevel traceLevel)
 {
     TraceLevel = traceLevel;
 }
Example #52
0
 public BusinessException(string message, TraceLevel traceLevel) : base(message)
 {
     TraceLevel = traceLevel;
 }
Example #53
0
 public MainLogger(Main main, string prefix, TraceLevel maxLevel = TraceLevel.Verbose)
 {
     Main     = main;
     Prefix   = prefix;
     MaxLevel = maxLevel;
 }
Example #54
0
 public bool IsEnabled(string category, TraceLevel level)
 {
     return(true);
 }
Example #55
0
 /// <summary>
 /// 普通信息构造
 /// </summary>
 /// <param name="info"></param>
 /// <param name="level"></param>
 public JobExecuteInfoArgs(Job sender, string info, TraceLevel level)
     : this(sender, "(信息)", 0, 0, DateTime.Now, true, info, level)
 {
 }
Example #56
0
 public SystemTraceWriter(IEventGenerator eventGenerator, TraceLevel level) : base(level)
 {
     _appName        = Environment.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteName);
     _subscriptionId = Utility.GetSubscriptionId();
     _eventGenerator = eventGenerator;
 }
Example #57
0
 public string GetWithTwoEnumParameters([FromUri] TraceLevel level, TraceKind kind)
 {
     return(level.ToString() + kind.ToString());
 }
 /// <summary>
 /// Creates an instance.
 /// </summary>
 /// <param name="level">The <see cref="TraceLevel"/> to use when filtering logs.</param>
 /// <param name="logger">The <see cref="ILogger"/> used to log the traces.</param>
 public LoggerTraceWriter(TraceLevel level, ILogger logger)
     : base(level)
 {
     _logger = logger;
 }
Example #59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MemoryTraceWriter"/> class.
 /// </summary>
 public MemoryTraceWriter()
 {
     LevelFilter    = TraceLevel.Verbose;
     _traceMessages = new Queue <string>();
 }
 public static void Write(TraceLevel level, string format, params object[] args)
 {
     InternalWrite(level, format, args);
 }