Git Product home page Git Product logo

hangfire.console.extensions's Introduction

Hangfire.Console.Extensions

NuGet version

Features

  • Makes it easier to use Hangfire.Console with .net core dependency injection

Setup

In .NET Core's Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHangfireConsoleExtensions();
}

Starting a job

To start a job you can use the IJobManager, it will automatically check if you are currently inside a job, if that is the case it will mark the started job as a Continuation.

Log

Instead of logging using the extension method on PerformContext you can now just use the ILogging and it will get logged to both normal logging facilities and Hangfire.Console.

Progressbar

To create a progress bar you can use IProgressBarFactory.

IJobCancellationToken

Just take the IJobCancellationToken as a constructor parameter to get a hold of the cancellation token.

Schedule jobs

Contains a extension method for AddOrUpdateManuallyTriggered if you have a job that should only be run manually.

Hangfire.Console.Extensions.Serilog

NuGet version

Usage with Serilog.Settings.Configuration

Add WithHangfireContext to Enrich and add Hangfire as a WriteTo target Example:

"Serilog": {
  "Enrich": [ "WithHangfireContext" ],
  "WriteTo": [
    {
      "Name": "Hangfire",
      "Args": {
        "restrictedToMinimumLevel": "Information"
      }
    }
  ]
}

hangfire.console.extensions's People

Contributors

abdruggi avatar alexispicot avatar anderssonpeter avatar sdebeul avatar steve-gombos avatar sucrose0413 avatar yoelweiner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

hangfire.console.extensions's Issues

Some minor Questions/Confirmations

Hiya,

I personally use the following interface to build jobs on:

    /// <summary>
    /// A rather empty base for options passed to a <see cref="IJob{TOptions}"/>
    /// NOTE When dealing with options note that the options class you use will be a DTO.
    ///      Json is used to serialize the class to a string and then it will be stored in the db.
    /// NOTE Interfaces or abstract classes are not supported! This means you can only use plain c# classes - keep this in mind. This includes valuetuples.
    /// </summary>
    [Serializable]
    public class JobOptionsBase
    {
    }

    public interface IJob<in TOptions> 
        where TOptions : JobOptionsBase, new()
    {
        public Task Run(PerformContext context, CancellationToken token, TOptions jobOptions = default);
    }

If i were to use this library, from what i can gather, i would need to change that interface and take out the Performcontext context and inject it in the constructor instead. Perhaps the same for the cancellationtoken.

Or could i leave this as - is?

Also in this sample i don't see a call to c.UseConsole(); in the startup, which adds the hangfire.console services. I also don't see this added in the AddHangfireConsoleExtensions` method - do i not need to call hangfire.console anymore?

This also uses GlobalJobFilters.Filters.Add(new HangfireSubscriber());
`

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire((serviceProvider, configuration) => configuration
                .UseConsole()
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                //.UseSqlServerStorage(@"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;"));
                .UseMemoryStorage());
            services.AddHangfireConsoleExtensions();
            services.AddHangfireServer();

            services.AddTransient<SampleJob>();
            services.AddTransient<ContinuationJob>();
        }

https://github.com/AnderssonPeter/Hangfire.Console.Extensions/blob/master/SampleWithSerilog/Startup.cs

Logging outside of hangfire job throws on missing PerformContext

Hi Peter,

Nice little extension!
I ran into a small issue when logging outside of a hangfire job. (Where there is no performContext).
It trows on enriching with the background jobid.
I understand this is due to asyncLocalLogFilter.Get() returning null.

/// <inheritdoc /> public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { // Create property value with PerformContext and put as "PerformContext" var prop = new LogEventProperty( "PerformContext", new PerformContextValue { PerformContext = asyncLocalLogFilter.Get() } ); logEvent.AddOrUpdateProperty(prop); }

So as a test I added a null check on it, and then just return from this Enrich method.
But then I'm in the situation that events written to the hangfire console don't end up in any other sink that uses property's
(SEQ in my case)

Would you have any insight on this?
br

Feature: injection of `IPerformContext`

IPerformingContextAccessor is a nice feature which helps with DI a lot, but still it makes mocking a bit inconvenient because the PerformingContext IPerformingContextAccessor.Get() must be set up which is not an interface, therefore, a new class PerformingContextMock must be created for this purpose.

Wouldn't it be more awesome if IPerformContext could be directly injected? In my project I created something like this:
Interfaces

public interface IProgressReporter
{
	void SetValue(double value);
}

public interface IPerformContext
{
	void WriteLine(string format, params object[] args);

	IProgressReporter StartProgress(string name);
}

Implementations

internal sealed class ProgressReporter : IProgressReporter
{
	private readonly IProgressBar? _progressBar;

	public ProgressReporter(IProgressBar? progressBar)
	{
		_progressBar = progressBar;
	}

	public void SetValue(double value) =>
		_progressBar?.SetValue(value);
}

internal sealed class PerformContext : IPerformContext
{
	private readonly IPerformingContextAccessor _performingContextAccessor;

	public PerformContext(IPerformingContextAccessor performingContextAccessor)
	{
		_performingContextAccessor = performingContextAccessor;
	}

	public void WriteLine(string format, params object[] args) =>
		_performingContextAccessor.Get()?.WriteLine(format, args);

	public IProgressReporter StartProgress(string name)
	{
		var progressBar = _performingContextAccessor.Get()
			?.WriteProgressBar(name);

		return new ProgressReporter(progressBar);
	}
}

I have to admit that it is still a bit unfinished because if IPerformingContextAccessor.Get() returns null (it means that a task is not scheduled but just called in debugging possibly) I wanted to make use of the Console.ProgressBar NuGet package.

If you think that this concept might be useful in Hangfire.Console.Extensions I guess I could help with a PR or something

[Q] Can't get this to work and log to the Console UI within Hangfire

Hey.

Might be me, but I'm using .net 7, Hangfire 1.8.3 and I cannot get this to work.

I'm configuring it in my program.cs
builder.Services.AddHangfireConsoleExtensions();

But I can't see any logs appearing within the hangfire jobs.

I'm using Microsoft.Extensions.Logging.ILogger<T>

Any ideas? Just no logs are outputting.

LogLevel.None not supported

Logging work as expected on other portions of the code
Trying to add Dataverse SDK and provide logger to the constructor using classical
provider.GetRequiredService<ILogger<IOrganizationService>>
This library tries to log something with LogLevel.None, not sure if it is useless or not but whatever

I'm encoutering issue while logging :

An error occurred while writing to logger(s). (Specified argument was out of the range of valid values. (Parameter 'logLevel'))

Microsoft.PowerPlatform.Dataverse.Client.Utils.DataverseConnectionException: An error occurred while writing to logger(s). (Specified argument was out of the range of valid values. (Parameter 'logLevel'))
 ---> System.AggregateException: An error occurred while writing to logger(s). (Specified argument was out of the range of valid values. (Parameter 'logLevel'))
 ---> System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter 'logLevel')
   at Hangfire.Console.Extensions.HangfireLogger.GetLogLevelString(LogLevel logLevel)
   at Hangfire.Console.Extensions.HangfireLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   at Microsoft.Extensions.Logging.Logger.<Log>g__LoggerLog|13_0[TState](LogLevel logLevel, EventId eventId, ILogger logger, Exception exception, Func`3 formatter, List`1& exceptions, TState& state)

I think the problem lies here :

public bool IsEnabled(LogLevel logLevel)
{
return true;
}

Whereas

private static string GetLogLevelString(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Trace:
return "trce";
case LogLevel.Debug:
return "dbug";
case LogLevel.Information:
return "info";
case LogLevel.Warning:
return "warn";
case LogLevel.Error:
return "fail";
case LogLevel.Critical:
return "crit";
default:
throw new ArgumentOutOfRangeException(nameof(logLevel));
}
}

Argument may be thrown if LogLevel.None is supplied

Hangfire property keep logs from going from Serilog to SEQ

In some instances of SEQ (2021.3) that support hosted environments, logs are not getting to SEQ.

In my local instance of SEQ (2021.3) they do get though. My DevOps team tells me there is nothing in the SEQ instances that would reject\filter logs out.

In addition to the SEQ write to, have a console and debug logger for Serilog. The logs are showing in VS output (where they don't visualize the log property, just the message).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.