本文整理汇总了C#中ITracer.Step方法的典型用法代码示例。如果您正苦于以下问题:C# ITracer.Step方法的具体用法?C# ITracer.Step怎么用?C# ITracer.Step使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ITracer
的用法示例。
在下文中一共展示了ITracer.Step方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RemoveFileSystemWatcher
private static void RemoveFileSystemWatcher(string key, ITracer tracer)
{
using (tracer.Step(String.Format("Disposing FileSystemWatcher for connectionId {0}", key)))
{
SimpleFileSystemWatcher temp;
if (_fileWatchers.TryRemove(key, out temp))
{
temp.Dispose();
}
}
}
示例2: StartProfileAsync
internal static async Task<ProfileResultInfo> StartProfileAsync(int processId, ITracer tracer = null)
{
tracer = tracer ?? NullTracer.Instance;
using (tracer.Step("ProfileManager.StartProfileAsync"))
{
// Check if the profiling is already running for the given process. If it does, then just return with 200.
if (_profilingList.ContainsKey(processId))
{
return new ProfileResultInfo(HttpStatusCode.OK, string.Empty);
}
int profilingSessionId = GetNextProfilingSessionId();
string arguments = System.Environment.ExpandEnvironmentVariables(string.Format("start {0} /attach:{1} /loadAgent:4EA90761-2248-496C-B854-3C0399A591A4;DiagnosticsHub.CpuAgent.dll /scratchLocation:%LOCAL_EXPANDED%\\Temp", profilingSessionId, processId));
var profileProcessResponse = await ExecuteProfilingCommandAsync(arguments, tracer);
if (profileProcessResponse.StatusCode != HttpStatusCode.OK)
{
return profileProcessResponse;
}
// This may fail if we got 2 requests at the same time to start a profiling session
// in that case, only 1 will be added and the other one will be stopped.
if (!_profilingList.TryAdd(processId, new ProfileInfo(profilingSessionId)))
{
tracer.TraceWarning("A profiling session was already running for process {0}, stopping profiling session {1}", processId, profilingSessionId);
await StopProfileInternalAsync(processId, profilingSessionId, true, tracer);
return new ProfileResultInfo(HttpStatusCode.OK, string.Empty);
}
tracer.Step("started session id: {0} for pid: {1}", profilingSessionId, processId);
EnsureIdleTimer();
return new ProfileResultInfo(HttpStatusCode.OK, string.Empty);
}
}
示例3: CleanBuild
private static void CleanBuild(ITracer tracer, string buildTempPath)
{
using (tracer.Step("Cleaning up temp files"))
{
try
{
FileSystemHelpers.DeleteDirectorySafe(buildTempPath);
}
catch (Exception ex)
{
tracer.TraceError(ex);
}
}
}
示例4: StopProfileAsync
internal static async Task<ProfileResultInfo> StopProfileAsync(int processId, ITracer tracer = null)
{
int profilingSessionId;
tracer = tracer ?? NullTracer.Instance;
using (tracer.Step("ProfileManager.StopProfileAsync"))
{
// check if the profiling is running for the given process. If it doesn't return 404.
if (!_profilingList.ContainsKey(processId))
{
return new ProfileResultInfo(HttpStatusCode.NotFound, string.Format("Profiling for process '{0}' is not running.", processId));
}
else
{
profilingSessionId = _profilingList[processId].SessionId;
}
var profileProcessResponse = await StopProfileInternalAsync(processId, profilingSessionId, false, tracer);
return profileProcessResponse;
}
}
示例5: FlushAllAsync
private static async Task FlushAllAsync(IProcess process, ITracer tracer, IdleManager idleManager, CancellationTokenSource cancellationTokenSource, IEnumerable<Task> tasks)
{
var prevActivity = DateTime.MinValue;
while (true)
{
// Wait for either delay or io tasks
var delay = Task.Delay(StandardOutputDrainTimeout, cancellationTokenSource.Token);
var stdio = Task.WhenAll(tasks);
var completed = await Task.WhenAny(stdio, delay);
// if delay commpleted first (meaning timeout), check if activity and continue to wait
if (completed == delay)
{
var lastActivity = idleManager.LastActivity;
if (lastActivity != prevActivity)
{
prevActivity = lastActivity;
continue;
}
}
// clean up all pending tasks by cancelling them
// this is important so we don't have runaway tasks
cancellationTokenSource.Cancel();
// in case of stdoutput/err have no activity within given time
// we force close all streams
if (completed == delay)
{
// TODO, suwatch: MDS Kudu SiteExtension
using (tracer.Step("Flush stdio and stderr have no activity within given time"))
{
bool exited = process.HasExited;
SafeCloseStream(process.StandardOutput.BaseStream);
SafeCloseStream(process.StandardError.BaseStream);
// this means no activity within given time
// and process has not exited
if (!exited)
{
throw new TimeoutException("Timeout draining standard input, output and error!");
}
}
}
// happy path
break;
}
}
示例6: Build
/// <summary>
/// Builds and deploys a particular changeset. Puts all build artifacts in a deployments/{id}
/// </summary>
private async Task Build(string id, ITracer tracer, IDisposable deployStep, IFileFinder fileFinder)
{
if (String.IsNullOrEmpty(id))
{
throw new ArgumentException("The id parameter is null or empty", "id");
}
ILogger logger = null;
IDeploymentStatusFile currentStatus = null;
try
{
logger = GetLogger(id);
ILogger innerLogger = logger.Log(Resources.Log_PreparingDeployment, TrimId(id));
currentStatus = _status.Open(id);
currentStatus.Complete = false;
currentStatus.StartTime = DateTime.UtcNow;
currentStatus.Status = DeployStatus.Building;
currentStatus.StatusText = String.Format(CultureInfo.CurrentCulture, Resources.Status_BuildingAndDeploying, id);
currentStatus.Save();
ISiteBuilder builder = null;
string repositoryRoot = _environment.RepositoryPath;
var perDeploymentSettings = DeploymentSettingsManager.BuildPerDeploymentSettingsManager(repositoryRoot, _settings);
try
{
using (tracer.Step("Determining deployment builder"))
{
builder = _builderFactory.CreateBuilder(tracer, innerLogger, perDeploymentSettings, fileFinder);
tracer.Trace("Builder is {0}", builder.GetType().Name);
}
}
catch (Exception ex)
{
// If we get a TargetInvocationException, use the inner exception instead to avoid
// useless 'Exception has been thrown by the target of an invocation' messages
var targetInvocationException = ex as System.Reflection.TargetInvocationException;
if (targetInvocationException != null)
{
ex = targetInvocationException.InnerException;
}
_globalLogger.Log(ex);
tracer.TraceError(ex);
innerLogger.Log(ex);
currentStatus.MarkFailed();
deployStep.Dispose();
return;
}
var context = new DeploymentContext
{
NextManifestFilePath = GetDeploymentManifestPath(id),
PreviousManifestFilePath = GetActiveDeploymentManifestPath(),
Tracer = tracer,
Logger = logger,
GlobalLogger = _globalLogger,
OutputPath = GetOutputPath(_environment, perDeploymentSettings),
};
if (context.PreviousManifestFilePath == null)
{
// In the first deployment we want the wwwroot directory to be cleaned, we do that using a manifest file
// That has the expected content of a clean deployment (only one file: hostingstart.html)
// This will result in KuduSync cleaning this file.
context.PreviousManifestFilePath = Path.Combine(_environment.ScriptPath, Constants.FirstDeploymentManifestFileName);
}
using (tracer.Step("Building"))
{
try
{
await builder.Build(context);
TryTouchWebConfig(context);
// Run post deployment steps
FinishDeployment(id, deployStep);
}
catch (Exception ex)
{
tracer.TraceError(ex);
currentStatus.MarkFailed();
// End the deploy step
deployStep.Dispose();
return;
//.........这里部分代码省略.........
示例7: GetProcessStep
private IDisposable GetProcessStep(ITracer tracer, string arguments)
{
return tracer.Step("Executing external process", new Dictionary<string, string>
{
{ "type", "process" },
{ "path", System.IO.Path.GetFileName(Path) },
{ "arguments", arguments }
});
}
示例8: IsAnyInstallationRequireRestart
/// <summary>
/// <para>Scan every site extensions, check if there is any successful installation</para>
/// <para>Looking for below cases:</para>
/// <para>if not install to webroot, trigger restart; if install to webroot and with applicationHost.xdt file, trigger restart.</para>
/// </summary>
/// <param name="siteExtensionStatusRoot">should be $ROOT\site\siteextensions</param>
/// <param name="siteExtensionRoot">should be $ROOT\SiteExtensions</param>
public static bool IsAnyInstallationRequireRestart(string siteExtensionStatusRoot, string siteExtensionRoot, ITracer tracer, IAnalytics analytics)
{
try
{
using (tracer.Step("Checking if there is any installation require site restart ..."))
{
string[] packageDirs = FileSystemHelpers.GetDirectories(siteExtensionStatusRoot);
// folder name is the package id
foreach (var dir in packageDirs)
{
try
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
var statusSettings = new SiteExtensionStatus(siteExtensionStatusRoot, dirInfo.Name, tracer);
if (statusSettings.IsSiteExtensionRequireRestart(siteExtensionRoot))
{
return true;
}
}
catch (Exception ex)
{
analytics.UnexpectedException(ex, trace: false);
tracer.TraceError(ex, "Failed to query {0} under {1}, continus to check others ...", _statusSettingsFileName, dir);
}
}
}
}
catch (Exception ex)
{
analytics.UnexpectedException(ex, trace: false);
tracer.TraceError(ex, "Not able to query directory under {0}", siteExtensionStatusRoot);
}
return false;
}
示例9: KillProcess
private static void KillProcess(string connectionId, ITracer tracer = null)
{
ProcessInfo process;
if (_processes.TryRemove(connectionId, out process))
{
tracer = tracer ?? NullTracer.Instance;
using (tracer.Step("process " + process.Process.Id + " killed!"))
{
process.Process.Kill(tracer);
}
lock (_processes)
{
if (_processes.Count == 0)
{
if (_idleTimer != null)
{
_idleTimer.Dispose();
_idleTimer = null;
}
}
}
}
}
示例10: InstallExtension
/// <summary>
/// <para>1. Download package</para>
/// <para>2. Generate xdt file if not exist</para>
/// <para>3. Deploy site extension job</para>
/// <para>4. Execute install.cmd if exist</para>
/// </summary>
private async Task<UIPackageMetadata> InstallExtension(UIPackageMetadata package, string installationDirectory, string feedUrl, SiteExtensionInfo.SiteExtensionType type, ITracer tracer)
{
try
{
EnsureInstallationEnviroment(installationDirectory, tracer);
string packageLocalFilePath = GetNuGetPackageFile(package.Identity.Id, package.Identity.Version.ToNormalizedString());
bool packageExisted = FileSystemHelpers.DirectoryExists(installationDirectory);
SourceRepository remoteRepo = GetRemoteRepository(feedUrl);
using (tracer.Step("Download site extension: {0}", package.Identity))
{
string extractPath = installationDirectory;
if (SiteExtensionInfo.SiteExtensionType.WebRoot == type)
{
extractPath = _environment.WebRootPath;
FileSystemHelpers.EnsureDirectory(extractPath);
}
// Copy/update content folder
// Copy/update nupkg file for package list/lookup
if (packageExisted)
{
await remoteRepo.UpdateLocalPackage(_localRepository, package.Identity, extractPath, packageLocalFilePath, tracer);
}
else
{
FileSystemHelpers.EnsureDirectory(installationDirectory);
await remoteRepo.DownloadPackageToFolder(package.Identity, extractPath, packageLocalFilePath);
}
if (SiteExtensionInfo.SiteExtensionType.WebRoot == type)
{
// if install to WebRoot, check if there is any xdt file come with package
// if there is one, move it to site extension folder
string xdtFile = Path.Combine(extractPath, Constants.ApplicationHostXdtFileName);
if (File.Exists(xdtFile))
{
tracer.Trace("Use xdt file from package.");
string newXdtFile = Path.Combine(installationDirectory, Constants.ApplicationHostXdtFileName);
tracer.Trace("Moving {0} to {1}", xdtFile, newXdtFile);
FileSystemHelpers.MoveFile(xdtFile, newXdtFile);
}
else
{
tracer.Trace("No xdt file come with package.");
}
}
}
// ignore below action if we install packge to wwwroot
if (SiteExtensionInfo.SiteExtensionType.WebRoot != type)
{
// If there is no xdt file, generate default.
using (tracer.Step("Check if applicationhost.xdt file existed."))
{
GenerateApplicationHostXdt(installationDirectory, '/' + package.Identity.Id, isPreInstalled: false, tracer: tracer);
}
using (tracer.Step("Trigger site extension job"))
{
OperationManager.Attempt(() => DeploySiteExtensionJobs(package.Identity.Id));
}
var externalCommandFactory = new ExternalCommandFactory(_environment, _settings, installationDirectory);
string installScript = Path.Combine(installationDirectory, _installScriptName);
if (FileSystemHelpers.FileExists(installScript))
{
using (tracer.Step("Execute install.cmd"))
{
OperationManager.Attempt(() =>
{
Executable exe = externalCommandFactory.BuildCommandExecutable(installScript,
installationDirectory,
_settings.GetCommandIdleTimeout(), NullLogger.Instance);
exe.ExecuteWithProgressWriter(NullLogger.Instance, _traceFactory.GetTracer(), String.Empty);
});
}
}
}
}
catch (Exception ex)
{
tracer.TraceError(ex);
FileSystemHelpers.DeleteDirectorySafe(installationDirectory);
throw;
}
return await _localRepository.GetLatestPackageById(package.Identity.Id);
}
示例11: Execute
public void Execute(ITracer tracer, Stream input, Stream output, string arguments, params object[] args)
{
using (GetProcessStep(tracer, arguments, args))
{
var process = CreateProcess(arguments, args);
Func<StreamReader, string> reader = (StreamReader streamReader) => streamReader.ReadToEnd();
Action<Stream, Stream, bool, Func<IDisposable>> copyStream = (Stream from, Stream to, bool closeAfterCopy, Func<IDisposable> step) =>
{
try
{
using (step())
{
from.CopyTo(to);
if (closeAfterCopy)
{
to.Close();
tracer.Trace("Stream closed after copy");
}
else
{
tracer.Trace("Stream left open after copy");
}
}
}
catch (Exception ex)
{
tracer.TraceError(ex);
throw;
}
};
IAsyncResult errorReader = reader.BeginInvoke(process.StandardError, null, null);
IAsyncResult inputResult = null;
if (input != null)
{
// Copy into the input stream, and close it to tell the exe it can process it
inputResult = copyStream.BeginInvoke(input,
process.StandardInput.BaseStream,
true,
() => tracer.Step("Copying input stream to stdin."),
null,
null);
}
// Copy the exe's output into the output stream
IAsyncResult outputResult = copyStream.BeginInvoke(process.StandardOutput.BaseStream,
output,
false,
() => tracer.Step("Copying stdout to output stream."),
null,
null);
process.WaitForExit();
// Wait for the input operation to complete
if (inputResult != null)
{
inputResult.AsyncWaitHandle.WaitOne();
}
// Wait for the output operation to be complete
outputResult.AsyncWaitHandle.WaitOne();
string error = reader.EndInvoke(errorReader);
tracer.Trace("Process dump", new Dictionary<string, string>
{
{ "outStream", "" },
{ "errorStream", error },
{ "type", "processOutput" }
});
if (process.ExitCode != 0)
{
throw new Exception(error);
}
}
}
示例12: ExecuteProfilingCommandAsync
private static async Task<ProfileResultInfo> ExecuteProfilingCommandAsync(string arguments, ITracer tracer)
{
MemoryStream outputStream = null;
MemoryStream errorStream = null;
try
{
tracer.Step("ProcessName:" + _processName + " arguments:" + arguments);
var exe = new Executable(_processName, Path.GetDirectoryName(_processName), TimeSpan.FromSeconds(ProcessExitTimeoutInSeconds));
outputStream = new MemoryStream();
errorStream = new MemoryStream();
tracer.Step("Path:" + exe.Path + " working directory:" + exe.WorkingDirectory);
int exitCode = await exe.ExecuteAsync(tracer, arguments, outputStream, errorStream);
string output = GetString(outputStream);
string error = GetString(errorStream);
tracer.Step(output);
if (exitCode != 0)
{
tracer.TraceError(string.Format(CultureInfo.InvariantCulture, "Starting process {0} failed with the following error code '{1}'.", _processName, exitCode));
return new ProfileResultInfo(HttpStatusCode.InternalServerError, "Profiling process failed with the following error code: " + exitCode);
}
else if (!string.IsNullOrEmpty(error))
{
tracer.TraceError(error);
return new ProfileResultInfo(HttpStatusCode.InternalServerError, "Profiling process failed with the following error: " + error);
}
return new ProfileResultInfo(HttpStatusCode.OK, string.Empty);
}
catch (Exception ex)
{
tracer.TraceError(ex);
return new ProfileResultInfo(HttpStatusCode.InternalServerError, ex.Message);
}
finally
{
if (outputStream != null)
{
outputStream.Dispose();
}
if (errorStream != null)
{
errorStream.Dispose();
}
}
}
示例13: StopProfileInternalAsync
private static async Task<ProfileResultInfo> StopProfileInternalAsync(int processId, int profilingSessionId, bool ignoreProfileFile, ITracer tracer = null)
{
tracer = tracer ?? NullTracer.Instance;
using (tracer.Step("ProfileManager.StopProfileInternalAsync"))
{
string profileFileFullPath = GetProfilePath(processId);
string profileFileName = Path.GetFileName(profileFileFullPath);
string arguments = string.Format("stop {0} /output:{1}", profilingSessionId, profileFileFullPath);
var profileProcessResponse = await ExecuteProfilingCommandAsync(arguments, tracer);
ProfileInfo removedId;
if (profileProcessResponse.StatusCode != HttpStatusCode.OK)
{
_profilingList.TryRemove(processId, out removedId);
return profileProcessResponse;
}
FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(profileFileFullPath));
tracer.Step("profile was saved to {0} successfully.", profileFileFullPath);
_profilingList.TryRemove(processId, out removedId);
if (ignoreProfileFile)
{
try
{
FileSystemHelpers.DeleteFile(profileFileFullPath);
}
catch
{
}
}
DisposeTimerIfNecessary();
return new ProfileResultInfo(HttpStatusCode.OK, string.Empty);
}
}
示例14: Build
/// <summary>
/// Builds and deploys a particular changeset. Puts all build artifacts in a deployments/{id}
/// </summary>
private void Build(string id, ITracer tracer, IDisposable deployStep)
{
if (String.IsNullOrEmpty(id))
{
throw new ArgumentException();
}
ILogger logger = null;
DeploymentStatusFile currentStatus = null;
IDisposable buildStep = null;
try
{
logger = GetLogger(id);
ILogger innerLogger = logger.Log(Resources.Log_PreparingDeployment, TrimId(id));
currentStatus = OpenStatusFile(id);
currentStatus.Complete = false;
currentStatus.StartTime = DateTime.Now;
currentStatus.Status = DeployStatus.Building;
currentStatus.StatusText = String.Format(CultureInfo.CurrentCulture, Resources.Status_BuildingAndDeploying, id);
currentStatus.Save(_fileSystem);
ReportStatus(id);
ISiteBuilder builder = null;
try
{
builder = _builderFactory.CreateBuilder(tracer, innerLogger);
}
catch (Exception ex)
{
_globalLogger.Log(ex);
tracer.TraceError(ex);
innerLogger.Log(ex);
MarkFailed(currentStatus);
ReportStatus(id);
deployStep.Dispose();
return;
}
buildStep = tracer.Step("Building");
var context = new DeploymentContext
{
ManifestWriter = GetDeploymentManifestWriter(id),
PreviousMainfest = GetActiveDeploymentManifestReader(),
Tracer = tracer,
Logger = logger,
GlobalLogger = _globalLogger,
OutputPath = _environment.DeploymentTargetPath,
};
builder.Build(context)
.Then(() =>
{
// End the build step
buildStep.Dispose();
// Run post deployment steps
FinishDeployment(id, tracer, deployStep);
})
.Catch(ex =>
{
// End the build step
buildStep.Dispose();
MarkFailed(currentStatus);
ReportStatus(id);
// End the deploy step
deployStep.Dispose();
});
}
catch (Exception ex)
{
tracer.TraceError(ex);
logger.LogUnexpetedError();
if (buildStep != null)
{
buildStep.Dispose();
}
deployStep.Dispose();
}
}
示例15: CreateAndPopulateStatusFile
private ILogger CreateAndPopulateStatusFile(ITracer tracer, string id, string deployer)
{
ILogger logger = GetLogger(id);
using (tracer.Step("Collecting changeset information"))
{
// Remove any old instance of a temporary deployment if exists
DeleteTemporaryDeployment();
// Create the status file and store information about the commit
DeploymentStatusFile statusFile = CreateStatusFile(id);
ChangeSet changeSet = _serverRepository.GetChangeSet(id);
statusFile.Message = changeSet.Message;
statusFile.Author = changeSet.AuthorName;
statusFile.Deployer = deployer;
statusFile.AuthorEmail = changeSet.AuthorEmail;
statusFile.Save(_fileSystem);
logger.Log(Resources.Log_NewDeploymentReceived);
}
return logger;
}