简体   繁体   中英

How do you use a .Net TextWriter with Azure WebJobs

I want to do some simple debugging, and Console.Writeline no longer seems to be supported by Azure WebJobs.

I know using a TextWriter class is the answer, and I just inject it into my method. What I don't understand is how I call that method. I cannot invalidate my Main method signature and inject it there.

What am I missing please?

public static void Main(TextWriter log)
{
    //This is is not valid
}

For continous webjob, you can do it like that :

class Program
{
    private static void Main()
    {
        var host = new JobHost();
        host.Call(typeof(Program).GetMethod("Start"));
        host.RunAndBlock();
    }

    [NoAutomaticTrigger]
    public static void Start(TextWriter textWriter)
    {

    }
}

While the above are correct you can also create your own custom TraceWriter instance that intercepts Trace calls in your application.

Example of a TraceWriter class:

using System.Diagnostics;
using Microsoft.Azure.WebJobs.Host;

namespace MiscOperations
{
    /// <summary>
    /// Custom <see cref="TraceWriter"/> demonstrating how JobHost logs/traces can
    /// be intercepted by user code.
    /// </summary>
    public class CustomTraceWriter : TraceWriter
    {
        public CustomTraceWriter(TraceLevel level)
            : base(level)
        {
        }

        public override void Trace(TraceEvent traceEvent)
        {
            // handle trace messages here
        }
    }
}

Then in your JobHostConfuration setup you register your instance of the TraceWriter class in the main method of the console application. Ie in Program.cs.

JobHostConfiguration config = new JobHostConfiguration()
{
    NameResolver = new ConfigNameResolver(),
};

// Demonstrates how the console trace level can be customized
config.Tracing.ConsoleLevel = TraceLevel.Verbose;

// Demonstrates how a custom TraceWriter can be plugged into the
// host to capture all logging/traces.
config.Tracing.Tracers.Add(new CustomTraceWriter(TraceLevel.Info));

JobHost host = new JobHost(config);
host.RunAndBlock();

This way you can do other things with the trace such as write to an external service or create alerts.

Taken from the Azure SKD Samples Gitthub

CustomTraceWriter.cs

Program.cs

I believe you need to add a QueueTrigger attribute to the signature and Azure will call it when an event occurs. For instance:

public static void ProcessQueueMessage([QueueTrigger("logqueue")] string logMessage, TextWriter logger)
{
    logger.WriteLine(logMessage);
}

See this link: https://azure.microsoft.com/en-us/documentation/articles/websites-dotnet-webjobs-sdk-storage-queues-how-to/#trigger

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM