本文整理汇总了C#中ITracer.Trace方法的典型用法代码示例。如果您正苦于以下问题:C# ITracer.Trace方法的具体用法?C# ITracer.Trace怎么用?C# ITracer.Trace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ITracer
的用法示例。
在下文中一共展示了ITracer.Trace方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TraceActivity
public TraceActivity(ITracer tracer, string displayName, params object[] args)
{
this.tracer = tracer;
this.displayName = displayName;
if (args != null && args.Length > 0)
this.displayName = string.Format(displayName, args, CultureInfo.CurrentCulture);
newId = Guid.NewGuid();
oldId = Trace.CorrelationManager.ActivityId;
if (oldId != Guid.Empty)
tracer.Trace(TraceEventType.Transfer, newId);
Trace.CorrelationManager.ActivityId = newId;
tracer.Trace(TraceEventType.Start, this.displayName);
}
示例2: TraceActivity
public TraceActivity(ITracer tracer, string displayName, params object[] args)
{
this.tracer = tracer;
this.displayName = displayName;
if (args != null && args.Length > 0)
this.displayName = string.Format(displayName, args, CultureInfo.CurrentCulture);
newId = Guid.NewGuid();
oldId = Trace.CorrelationManager.ActivityId;
tracer.Trace(TraceEventType.Transfer, this.newId);
Trace.CorrelationManager.ActivityId = newId;
// The XmlWriterTraceListener expects Start/Stop events to receive an XPathNavigator
// with XML in a specific format so that the Service Trace Viewer can properly render
// the activity graph.
tracer.Trace(TraceEventType.Start, new ActivityData(this.displayName, true));
}
示例3: GetTriggerInputsAsync
private async Task<JArray> GetTriggerInputsAsync(ITracer tracer)
{
JArray inputs = new JArray();
foreach (var functionJson in await ListFunctionsConfigAsync())
{
try
{
JToken disabled;
if (functionJson.Config.TryGetValue("disabled", out disabled) && (bool)disabled)
{
tracer.Trace(String.Format("{0} is disabled", functionJson));
continue;
}
foreach (JObject input in functionJson.Config.Value<JArray>("bindings"))
{
var type = input.Value<string>("type");
if (type.EndsWith("Trigger", StringComparison.OrdinalIgnoreCase))
{
tracer.Trace(String.Format("Sync {0} of {1}", type, functionJson.Name));
inputs.Add(input);
}
else
{
tracer.Trace(String.Format("Skip {0} of {1}", type, functionJson.Name));
}
}
}
catch (Exception ex)
{
tracer.Trace(String.Format("{0} is invalid. {1}", functionJson.Name, ex.Message));
}
}
return inputs;
}
示例4: GetTotalProcessorTime
/// <summary>
/// Calculates the sum of TotalProcessorTime for the current process and all its children.
/// </summary>
public static TimeSpan GetTotalProcessorTime(this Process process, ITracer tracer)
{
try
{
var processes = process.GetChildren().Concat(new[] { process }).Select(p => new { Name = p.ProcessName, Id = p.Id, Cpu = p.TotalProcessorTime });
var totalTime = TimeSpan.FromTicks(processes.Sum(p => p.Cpu.Ticks));
var info = String.Join("+", processes.Select(p => String.Format("{0}({1},{2:0.000}s)", p.Name, p.Id, p.Cpu.TotalSeconds)).ToArray());
tracer.Trace("Cpu: {0}=total({1:0.000}s)", info, totalTime.TotalSeconds);
return totalTime;
}
catch (Exception ex)
{
tracer.TraceError(ex);
}
return process.TotalProcessorTime;
}
示例5: Execute
public Tuple<string, string> Execute(ITracer tracer, string arguments, params object[] args)
{
using (GetProcessStep(tracer, arguments, args))
{
var process = CreateProcess(arguments, args);
Func<StreamReader, string> reader = (StreamReader streamReader) => streamReader.ReadToEnd();
IAsyncResult outputReader = reader.BeginInvoke(process.StandardOutput, null, null);
IAsyncResult errorReader = reader.BeginInvoke(process.StandardError, null, null);
process.StandardInput.Close();
process.WaitForExit();
string output = reader.EndInvoke(outputReader);
string error = reader.EndInvoke(errorReader);
tracer.Trace("Process dump", new Dictionary<string, string>
{
{ "outStream", output },
{ "errorStream", error },
{ "type", "processOutput" }
});
// Sometimes, we get an exit code of 1 even when the command succeeds (e.g. with 'git reset .').
// So also make sure there is an error string
if (process.ExitCode != 0)
{
string text = String.IsNullOrEmpty(error) ? output : error;
throw new Exception(text);
}
return Tuple.Create(output, error);
}
}
示例6: CreateBuilder
public ISiteBuilder CreateBuilder(ITracer tracer, ILogger logger, IDeploymentSettingsManager settings, IFileFinder fileFinder)
{
string repositoryRoot = _environment.RepositoryPath;
// Use the cached vs projects file finder for: a. better performance, b. ignoring solutions/projects under node_modules
fileFinder = new CachedVsProjectsFileFinder(fileFinder);
// If there's a custom deployment file then let that take over.
var command = settings.GetValue(SettingsKeys.Command);
if (!String.IsNullOrEmpty(command))
{
return new CustomBuilder(_environment, settings, _propertyProvider, repositoryRoot, command);
}
// If the user provided specific generator arguments, that overrides any detection logic
string scriptGeneratorArgs = settings.GetValue(SettingsKeys.ScriptGeneratorArgs);
if (!String.IsNullOrEmpty(scriptGeneratorArgs))
{
return new CustomGeneratorCommandSiteBuilder(_environment, settings, _propertyProvider, repositoryRoot, scriptGeneratorArgs);
}
// If the repository has an explicit pointer to a project path to be deployed
// then use it.
string targetProjectPath = settings.GetValue(SettingsKeys.Project);
if (!String.IsNullOrEmpty(targetProjectPath))
{
tracer.Trace("Specific project was specified: " + targetProjectPath);
targetProjectPath = Path.GetFullPath(Path.Combine(repositoryRoot, targetProjectPath.TrimStart('/', '\\')));
// Try to resolve the project
return ResolveProject(repositoryRoot,
targetProjectPath,
settings,
fileFinder,
tryWebSiteProject: true,
searchOption: SearchOption.TopDirectoryOnly);
}
// Get all solutions in the current repository path
var solutions = VsHelper.GetSolutions(repositoryRoot, fileFinder).ToList();
if (!solutions.Any())
{
return ResolveProject(repositoryRoot,
settings,
fileFinder,
searchOption: SearchOption.AllDirectories);
}
// More than one solution is ambiguous
if (solutions.Count > 1)
{
// TODO: Show relative paths in error messages
ThrowAmbiguousSolutionsError(solutions);
}
// We have a solution
VsSolution solution = solutions[0];
// We need to determine what project to deploy so get a list of all web projects and
// figure out with some heuristic, which one to deploy.
// TODO: Pick only 1 and throw if there's more than one
VsSolutionProject project = solution.Projects.Where(p => p.IsWap || p.IsWebSite || p.IsAspNetCore).FirstOrDefault();
if (project == null)
{
// Try executable type project
project = solution.Projects.Where(p => p.IsExecutable).FirstOrDefault();
if (project != null)
{
return new DotNetConsoleBuilder(_environment,
settings,
_propertyProvider,
repositoryRoot,
project.AbsolutePath,
solution.Path);
}
logger.Log(Resources.Log_NoDeployableProjects, solution.Path);
return ResolveNonAspProject(repositoryRoot, null, settings);
}
if (project.IsWap)
{
return new WapBuilder(_environment,
settings,
_propertyProvider,
repositoryRoot,
project.AbsolutePath,
solution.Path);
}
if (project.IsAspNetCore)
{
return new AspNetCoreBuilder(_environment,
settings,
_propertyProvider,
//.........这里部分代码省略.........
示例7: EnumeratePlugins
// Enumerate plugins according to the specified node.
private IEnumerable<Plugin> EnumeratePlugins(PluginManager manager, Assembly assembly, PluginManifest.AssemblyEntry assemblyEntry, ITracer tracer)
{
foreach (string pluginTypeName in assemblyEntry.PluginTypes) {
Type pluginType;
try {
pluginType = assembly.GetType(pluginTypeName);
}
catch (Exception) {
tracer.Trace("PluginManager.Messages.TypeLoadError", assembly.CodeBase, pluginTypeName);
continue;
}
if (pluginType == null) {
tracer.Trace("PluginManager.Messages.TypeLoadError", assembly.CodeBase, pluginTypeName);
continue;
}
Plugin plugin = new Plugin(manager, assembly, pluginType);
yield return plugin;
}
}
示例8: TraceActivity
public TraceActivity(ITracer tracer, string format, params object[] args)
{
this.displayName = format;
if (args != null && args.Length > 0)
this.args = args;
this.tracer = tracer;
this.newId = Guid.NewGuid();
this.oldId = Trace.CorrelationManager.ActivityId;
if (this.oldId != Guid.Empty)
tracer.Trace(TraceEventType.Transfer, this.newId);
Trace.CorrelationManager.ActivityId = newId;
if (this.args == null)
{
this.tracer.Trace(TraceEventType.Start, this.displayName);
//Trace.CorrelationManager.StartLogicalOperation(this.displayName);
}
else
{
this.tracer.Trace(TraceEventType.Start, this.displayName, args);
//Trace.CorrelationManager.StartLogicalOperation(string.Format(displayName, args));
}
}
示例9: Execute
public Tuple<string, string> Execute(ITracer tracer, Func<string, bool> onWriteOutput, Func<string, bool> onWriteError, Encoding encoding, string arguments, params object[] args)
{
using (GetProcessStep(tracer, arguments, args))
{
Process process = CreateProcess(arguments, args);
process.EnableRaisingEvents = true;
var errorBuffer = new StringBuilder();
var outputBuffer = new StringBuilder();
var idleManager = new IdleManager(Path, IdleTimeout, tracer);
process.OutputDataReceived += (sender, e) =>
{
idleManager.UpdateActivity();
if (e.Data != null)
{
if (onWriteOutput(e.Data))
{
outputBuffer.AppendLine(Encoding.UTF8.GetString(encoding.GetBytes(e.Data)));
}
}
};
process.ErrorDataReceived += (sender, e) =>
{
idleManager.UpdateActivity();
if (e.Data != null)
{
if (onWriteError(e.Data))
{
errorBuffer.AppendLine(Encoding.UTF8.GetString(encoding.GetBytes(e.Data)));
}
}
};
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
try
{
idleManager.WaitForExit(process);
}
catch (Exception ex)
{
onWriteError(ex.Message);
throw;
}
tracer.Trace("Process dump", new Dictionary<string, string>
{
{ "exitCode", process.ExitCode.ToString() },
{ "type", "processOutput" }
});
string output = outputBuffer.ToString().Trim();
string error = errorBuffer.ToString().Trim();
if (process.ExitCode != 0)
{
string text = String.IsNullOrEmpty(error) ? output : error;
throw new CommandLineException(text)
{
ExitCode = process.ExitCode,
Output = output,
Error = error
};
}
return Tuple.Create(output, error);
}
}
示例10: GenerateApplicationHostXdt
private static void GenerateApplicationHostXdt(string installationDirectory, string relativeUrl, bool isPreInstalled, ITracer tracer = null)
{
// If there is no xdt file, generate default.
FileSystemHelpers.CreateDirectory(installationDirectory);
string xdtPath = Path.Combine(installationDirectory, Constants.ApplicationHostXdtFileName);
if (!FileSystemHelpers.FileExists(xdtPath))
{
if (tracer != null)
{
tracer.Trace("Missing xdt file, creating one.");
}
string physicalPath = isPreInstalled ? "%XDT_LATEST_EXTENSIONPATH%" : "%XDT_EXTENSIONPATH%";
string xdtContent = CreateDefaultXdtFile(relativeUrl, physicalPath);
OperationManager.Attempt(() => FileSystemHelpers.WriteAllText(xdtPath, xdtContent));
}
}
示例11: TryInstallExtension
private async Task<SiteExtensionInfo> TryInstallExtension(string id, string version, string feedUrl, SiteExtensionInfo.SiteExtensionType type, ITracer tracer)
{
SiteExtensionInfo info = null;
HttpStatusCode status = HttpStatusCode.OK; // final status when success
bool alreadyInstalled = false;
if (_preInstalledExtensionDictionary.ContainsKey(id))
{
tracer.Trace("Pre-installed site extension found: {0}, not going to perform new installation.", id);
info = EnablePreInstalledExtension(_preInstalledExtensionDictionary[id], tracer);
alreadyInstalled = true;
}
else
{
try
{
// Check if site extension already installed (id, version, feedUrl), if already install return right away
if (await this.IsSiteExtensionInstalled(id, version, feedUrl))
{
// package already installed, return package from local repo.
tracer.Trace("Package {0} with version {1} from {2} already installed.", id, version, feedUrl);
info = await GetLocalExtension(id);
alreadyInstalled = true;
}
else
{
JsonSettings siteExtensionSettings = GetSettingManager(id);
feedUrl = (string.IsNullOrEmpty(feedUrl) ? siteExtensionSettings.GetValue(_feedUrlSetting) : feedUrl);
SourceRepository remoteRepo = GetRemoteRepository(feedUrl);
UIPackageMetadata localPackage = null;
UIPackageMetadata repoPackage = null;
if (this.IsInstalledToWebRoot(id))
{
// override WebRoot type from setting
// WebRoot is a special type that install package to wwwroot, when perform update we need to update new content to wwwroot even if type is not specified
type = SiteExtensionInfo.SiteExtensionType.WebRoot;
}
if (string.IsNullOrWhiteSpace(version))
{
using (tracer.Step("Version is null, search latest package by id: {0}, will not search for unlisted package.", id))
{
repoPackage = await remoteRepo.GetLatestPackageById(id);
}
}
else
{
using (tracer.Step("Search package by id: {0} and version: {1}, will also search for unlisted package.", id, version))
{
repoPackage = await remoteRepo.GetPackageByIdentity(id, version);
}
}
if (repoPackage != null)
{
using (tracer.Step("Install package: {0}.", id))
{
string installationDirectory = GetInstallationDirectory(id);
localPackage = await InstallExtension(repoPackage, installationDirectory, feedUrl, type, tracer);
siteExtensionSettings.SetValues(new KeyValuePair<string, JToken>[] {
new KeyValuePair<string, JToken>(_versionSetting, localPackage.Identity.Version.ToNormalizedString()),
new KeyValuePair<string, JToken>(_feedUrlSetting, feedUrl),
new KeyValuePair<string, JToken>(_installUtcTimestampSetting, DateTime.UtcNow.ToString("u")),
new KeyValuePair<string, JToken>(_packageType, Enum.GetName(typeof(SiteExtensionInfo.SiteExtensionType), type))
});
}
}
info = await ConvertLocalPackageToSiteExtensionInfo(localPackage, checkLatest: true, tracer: tracer);
}
}
catch (FileNotFoundException ex)
{
_analytics.UnexpectedException(
ex,
method: "PUT",
path: string.Format(CultureInfo.InvariantCulture, "/api/siteextensions/{0}", id),
result: Constants.SiteExtensionProvisioningStateFailed,
message: string.Format(CultureInfo.InvariantCulture, "{{\"version\": {0}, \"feed_url\": {1}}}", version, feedUrl),
trace: false);
tracer.TraceError(ex);
info = new SiteExtensionInfo();
info.Id = id;
info.ProvisioningState = Constants.SiteExtensionProvisioningStateFailed;
info.Comment = ex.ToString();
status = HttpStatusCode.NotFound;
}
catch (WebException ex)
{
_analytics.UnexpectedException(
ex,
method: "PUT",
path: string.Format(CultureInfo.InvariantCulture, "/api/siteextensions/{0}", id),
result: Constants.SiteExtensionProvisioningStateFailed,
message: string.Format(CultureInfo.InvariantCulture, "{{\"version\": {0}, \"feed_url\": {1}}}", version, feedUrl),
trace: false);
tracer.TraceError(ex);
//.........这里部分代码省略.........
示例12: CreateBuilder
public ISiteBuilder CreateBuilder(ITracer tracer, ILogger logger)
{
string repositoryRoot = _environment.RepositoryPath;
var configuration = new DeploymentConfiguration(repositoryRoot);
// If there's a custom deployment file then let that take over.
if (!String.IsNullOrEmpty(configuration.Command))
{
return new CustomBuilder(repositoryRoot, _environment.TempPath, configuration.Command, _propertyProvider);
}
// If the repository has an explicit pointer to a project path to be deployed
// then use it.
string targetProjectPath = configuration.ProjectPath;
if (!String.IsNullOrEmpty(targetProjectPath))
{
tracer.Trace("Found .deployment file in repository");
// Try to resolve the project
return ResolveProject(repositoryRoot,
targetProjectPath,
tryWebSiteProject: true,
searchOption: SearchOption.TopDirectoryOnly);
}
// Get all solutions in the current repository path
var solutions = VsHelper.GetSolutions(repositoryRoot).ToList();
if (!solutions.Any())
{
return ResolveProject(repositoryRoot,
searchOption: SearchOption.AllDirectories);
}
// More than one solution is ambiguous
if (solutions.Count > 1)
{
// TODO: Show relative paths in error messages
ThrowAmbiguousSolutionsError(solutions);
}
// We have a solution
VsSolution solution = solutions[0];
// We need to determine what project to deploy so get a list of all web projects and
// figure out with some heuristic, which one to deploy.
// TODO: Pick only 1 and throw if there's more than one
VsSolutionProject project = solution.Projects.Where(p => p.IsWap || p.IsWebSite).FirstOrDefault();
if (project == null)
{
logger.Log(Resources.Log_NoDeployableProjects, solution.Path);
return new BasicBuilder(repositoryRoot, _environment.TempPath, _environment.ScriptPath);
}
if (project.IsWap)
{
return new WapBuilder(_settings,
_propertyProvider,
repositoryRoot,
project.AbsolutePath,
_environment.TempPath,
_environment.NuGetCachePath,
solution.Path);
}
return new WebSiteBuilder(_propertyProvider,
repositoryRoot,
project.AbsolutePath,
_environment.TempPath,
_environment.NuGetCachePath,
solution.Path);
}
示例13: FireSyncTriggers
private void FireSyncTriggers(ITracer tracer)
{
tracer.Trace("FunctionController.FireSyncTriggers");
// create background tracer independent of request lifetime
var bgTracer = new XmlTracer(_environment.TracePath, tracer.TraceLevel);
// start new task to detach from request sync context
Task.Run(async () =>
{
using (bgTracer.Step(XmlTracer.BackgroundTrace, new Dictionary<string, string>
{
{ "url", "/api/functions/synctriggers" },
{ "method", "POST" }
}))
{
try
{
await _manager.SyncTriggersAsync(bgTracer);
}
catch (Exception ex)
{
bgTracer.TraceError(ex);
}
}
});
}
示例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("The id parameter is null or empty", "id");
}
ILogger logger = null;
IDeploymentStatusFile currentStatus = null;
IDisposable buildStep = 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);
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;
}
buildStep = tracer.Step("Building");
var context = new DeploymentContext
{
ManifestWriter = GetDeploymentManifestWriter(id),
PreviousManifest = GetActiveDeploymentManifestReader(),
Tracer = tracer,
Logger = logger,
GlobalLogger = _globalLogger,
OutputPath = GetOutputPath(_environment, perDeploymentSettings),
};
context.NextManifestFilePath = context.ManifestWriter.ManifestFilePath;
if (context.PreviousManifest == 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.PreviousManifest = new DeploymentManifest(Path.Combine(_environment.ScriptPath, Constants.FirstDeploymentManifestFileName));
}
context.PreviousManifestFilePath = context.PreviousManifest.ManifestFilePath;
builder.Build(context)
.Then(() =>
{
// End the build step
buildStep.Dispose();
TryTouchWebConfig(context);
// Run post deployment steps
FinishDeployment(id, deployStep);
})
.Catch(ex =>
{
// End the build step
//.........这里部分代码省略.........
示例15: GetParentProcess
/// <summary>
/// Get parent process.
/// </summary>
public static Process GetParentProcess(this Process process, ITracer tracer)
{
IntPtr processHandle;
if (!process.TryGetProcessHandle(out processHandle))
{
return null;
}
var pbi = new ProcessNativeMethods.ProcessInformation();
try
{
int returnLength;
int status = ProcessNativeMethods.NtQueryInformationProcess(processHandle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength);
if (status != 0)
{
throw new Win32Exception(status);
}
return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32());
}
catch (Exception ex)
{
if (!process.ProcessName.Equals("w3wp", StringComparison.OrdinalIgnoreCase))
{
tracer.Trace("GetParentProcess of {0}({1}) failed with {2}", process.ProcessName, process.Id, ex);
}
return null;
}
}