GithubHelp home page GithubHelp logo

pieceofsummer / hangfire.console Goto Github PK

View Code? Open in Web Editor NEW
429.0 429.0 79.0 271 KB

Job console extension for Hangfire

License: MIT License

C# 91.46% JavaScript 5.78% CSS 2.76%
dashboard extension hangfire logging

hangfire.console's People

Contributors

odinserj avatar pieceofsummer 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hangfire.console's Issues

Progressbar not showing

I'm trying to use the progressbar but isn't working.

That's my code:

if (listIds.Any())
{
	int count = 0;
	context.WriteLine("####### Progresso da Atualização #######");
	var bar = context.WriteProgressBar("Progresso total", 0, ConsoleTextColor.DarkBlue);

	foreach (var id in listIds)
	{
		var message = AddMedico(id);

		count = count + 1;

		bar.SetValue((count * 100) / listIds.Count);

		listReturn.Add(new Tuple<string, string>($"Medico {id.ToString()}", message));
		context.WriteLine($"Medico {id.ToString()}: {message}");

	}
}
else
{
	...
}

How can I get the PerformContext?

I created a demo task like this.

    public static class DataMaintainTask
    {
        public static void DemoTask(PerformContext context)
        {
            // create progress bar
            var progress = context.WriteProgressBar();
            // update value for previously created progress bar
            progress.SetValue(100);
        }
    }

But,how can I add the task to hangfire? I Use the following method will get an error.
I don't know how to get the PerformContext.

RecurringJob.AddOrUpdate("some-id", () => DataMaintainTask.DemoTask(), Cron.Hourly);

image

Sql Server performance on large lists and Progress Bar

When "IProgressBar.SetValue" is called with a difference of only 0.1%, it triggers an update. It would perform better if the value was only updated when the value changes by a certain percent (like 1%). Is there a way to decrease the precision? instead of 100 updates it has 1000 updates.

Newtonsoft.Json version

Hello.

Would you consider changing the dependency requirements for Newtonsoft.Json to match Hangfire.Core for .Net 4.5?

The core has this dependency:
Newtonsoft.Json (>= 5.0.0)

With Progress, could auto create a bar

Simple Request, can this project add a WithProgress option without a progress bar?

public static async Task WithProgress<T>(this PerformContext performContext, IEnumerable<T> rows) { var bar = performContext.WriteProgressBar(); rows.WithProgress(bar, rows.Count()); }

ExpireIn console sessions

Our jobs each have custom expire history settings.
So, I would like the ExpireIn to just go along with the job history setting.

Should I just set ExpireIn to super far in the future....and let it be removed with the job history (assume it will) or should there be another setting for expiration?

Ability to render html

Is there a way to hit a GET route and then render the HTML content.

Basically I have html as a string and would like to render it instead of printing out the raw html.

Can't see console

GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection").UseConsole();
app.UseHangfireDashboard();
app.UseHangfireServer();

is there anything wrong with the way I'm doing it?
I can only see the console in the Processing Tab?
You said if I use dashboard and server separately I should call on both, how to do that?

Incompatible with Postgres? InvalidCastException

Whenever a job should complete, it is failing because of an error here:

System.InvalidCastException

Unable to cast object of type 'Hangfire.PostgreSql.PostgreSqlWriteOnlyTransaction' to type 'Hangfire.Storage.JobStorageTransaction'.

System.InvalidCastException: Unable to cast object of type 'Hangfire.PostgreSql.PostgreSqlWriteOnlyTransaction' to type 'Hangfire.Storage.JobStorageTransaction'.
   at Hangfire.Console.Storage.ConsoleStorage.Expire(ConsoleId consoleId, TimeSpan expireIn)
   at Hangfire.Console.Server.ConsoleServerFilter.OnPerformed(PerformedContext context)
   at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter filter, PerformingContext preContext, Func`1 continuation)

I am investigating this now but recording here for others to find.

Named progress Bar

Can I give a name to the ProgressBar?
Several processes are performed and each carries a named. Each process has its own ProgressBar
template

Orphaned console rows in Set table

Hi

I'm using a global filter .UseFilter(new AutomaticRetryAttribute { Attempts = 0, LogEvents = true }) on my jobs.

When a job fails, it goes to the "Failed" section on the dashboard. At this time, the console:xxxx rows in the Set sql table have a null ExpireAt value.

When I delete the job from the dashboard, the ExpireAt is still null.

It seems that this results in the rows never getting cleaned up? I had 2 million console:xxx rows in the table.

If the job fishes succesfully, then the ExpireAt gets a value.

Do I need to do something differently to get the rows cleaned up automatically? Or should I make my own job that cleans them on a regular basis?

Log items can sometimes render in the wrong order.

Hello, thanks for your wonderful work on this project.

I've ran into a strange issue where sometimes log entries appear out of order, even though their timestamps are correct. See below where "Creating new subscription..." was written at 9.321, before the previous three messages, but rendered at the end

screen-shot

I can verify that the context.WriteLine(...) calls happened in the same order of the timestamps, and "Done." is written as the last line of the Task.

My suggested fix would be to order the output of ConsoleRenderer.ReadLines here by timestamp.

Display Progress Bar on Remote Website

Good Evening,

Is there any way (using an API, or something) to display the progress bar of a job on a remote site? I'd like to provide end users with a view of the progress of their jobs - without giving them access to the Hangfire dashboard.

Thanks

For any job, the last successful call to WriteLine seems to be ignored, using redis backend.

Given the following example job:

public async Task Execute(PerformContext ctx, IJobCancellationToken cancellationToken)
{
    var things = await _dataContext.Things.ToListAsync();

    foreach (var thing in things)
    {
        cancellationToken.ThrowIfCancellationRequested();
        Thread.Sleep(TimeSpan.FromSeconds(1));
        ctx.WriteLine($"Do something with the thing: {thing.id}");
    }
}

For arguments sake lets say there were 5 things in the database.
Well I would only ever see 4 lines in the Hangfire Console output.

If I run the task like this:

public async Task Execute(PerformContext ctx, IJobCancellationToken cancellationToken)
{
    var things = await _dataContext.Things.ToListAsync();

    foreach (var thing in things)
    {
        cancellationToken.ThrowIfCancellationRequested();
        Thread.Sleep(TimeSpan.FromSeconds(1));
        ctx.WriteLine($"Do something with the thing: {thing.id}");
    }

    ctx.WriteLine();
}

I now see all 5 lines, the 6th line is however ignored. For now my workaround is to just call a blank WriteLine directly after every other call to WriteLine, the output is now spaced out of course but at least I see everything I expect to see.

Any ideas?

How to use it with MongoDB?

I tried to use it with HangFire.Mongo 0.3.2 however after defining the storage I'm unable to resolve the .UseConsole().

PerformContext.WriteLine is not thread safe

Running the below code (using SQL server) throws a TransactionInDoubtException error:

var tenants = new List<int>{ 1, 2, 3, 4, 5, 6 };
Parallel.ForEach(tenants, new ParallelOptions { MaxDegreeOfParallelism = 3 }, tenant =>
{
context.WriteLine("test message");
}

Update WriteLine Value

There are certain cases I'd like to update a console write. Weather it's printing out multiple parallel states of multiple processes, or even just printing out a "Current/Total" Count (ex: 24/30,000).

Is there anyway I can do this with the current lib?

css styles not working

Hey,
I am using hangfire version 1.6.17.0. I've followed all the steps. Eveything works fine i see the logs but the design is not well. I've downloaded the source code and found the css file. Then i referenced it in browser console. Now eveything works fine. But it is just temporarily. Then I had to append a line which adds the style.css to the body html. Recompiled the project and referenced it manually. Until you fix the issue :)

PerformContext.WriteLine still not threadsafe

I get the following exception when calling PerformContext.WriteLine in a multi-threaded context. First, exception (1) is thrown once, followed by many throws of exception (2) for each other thread that makes a call to WriteLine after exception (1) is thrown. After exception (1) has been thrown, all subsequent calls to ThrowIfCancellationRequested throw exception (3)

This job in question has [DisableConcurrentExecution], and also checks Hangfire.Server.ServerJobCancellationToken.ThrowIfCancellationRequested() periodically.

Exception (1)

 System.Transactions.TransactionAbortedException
              HResult=0x80131501
              Message=The transaction has aborted.
              Source=System.Transactions
              StackTrace:
               at System.Transactions.TransactionStateAborted.EndCommit(InternalTransaction tx)
               at System.Transactions.CommittableTransaction.Commit()
               at System.Transactions.TransactionScope.InternalDispose()
               at System.Transactions.TransactionScope.Dispose()
               at Hangfire.SqlServer.SqlServerStorage.UseTransaction[T](DbConnection dedicatedConnection, Func`3 func, Nullable`1 isolationLevel)
               at Hangfire.SqlServer.SqlServerStorage.UseTransaction(DbConnection dedicatedConnection, Action`2 action)
               at Hangfire.SqlServer.SqlServerWriteOnlyTransaction.Commit()
               at Hangfire.Console.Storage.ConsoleStorage.AddLine(ConsoleId consoleId, ConsoleLine line)
               at Hangfire.Console.Server.ConsoleContext.AddLine(ConsoleLine line)
               at Hangfire.Console.ConsoleExtensions.WriteLine(PerformContext context, String value)

            Inner Exception 1:
            SqlException: The transaction operation cannot be performed because there are pending requests working on this transaction.

Exception (2)

System.InvalidOperationException
             HResult=0x80131509
             Message=The requested operation cannot be completed because the connection has been broken.
             Source=System.Data
             StackTrace:
              at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionRequest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
              at System.Data.SqlClient.SqlDelegatedTransaction.Initialize()
              at System.Transactions.TransactionStatePSPEOperation.PSPEInitialize(InternalTransaction tx, IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
              at System.Transactions.TransactionStateActive.EnlistPromotableSinglePhase(InternalTransaction tx, IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Transaction atomicTransaction, Guid promoterType)
              at System.Transactions.Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
              at System.Transactions.Transaction.EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification)
              at System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx)
              at System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
              at System.Data.SqlClient.SqlInternalConnection.EnlistTransaction(Transaction transaction)
              at System.Data.SqlClient.SqlConnection.EnlistTransaction(Transaction transaction)
              at Hangfire.SqlServer.SqlServerStorage.<>c__DisplayClass27_0`1.<UseTransaction>b__0(DbConnection connection)
              at Hangfire.SqlServer.SqlServerStorage.UseConnection[T](DbConnection dedicatedConnection, Func`2 func)
              at Hangfire.SqlServer.SqlServerStorage.UseTransaction[T](DbConnection dedicatedConnection, Func`3 func, Nullable`1 isolationLevel)
              at Hangfire.SqlServer.SqlServerStorage.UseTransaction(DbConnection dedicatedConnection, Action`2 action)
              at Hangfire.SqlServer.SqlServerWriteOnlyTransaction.Commit()
              at Hangfire.Console.Storage.ConsoleStorage.AddLine(ConsoleId consoleId, ConsoleLine line)
              at Hangfire.Console.Server.ConsoleContext.AddLine(ConsoleLine line)
              at Hangfire.Console.ConsoleExtensions.WriteLine(PerformContext context, String value)

Exception (3)

System.Data.SqlClient.SqlException (0x80131904): Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at Dapper.SqlMapper.ExecuteReaderWithFlagsFallback(IDbCommand cmd, Boolean wasClosed, CommandBehavior behavior)
   at Dapper.SqlMapper.<QueryImpl>d__125`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType)
   at Hangfire.SqlServer.SqlServerConnection.<>c__DisplayClass9_0.<GetStateData>b__0(DbConnection connection)
   at Hangfire.SqlServer.SqlServerStorage.UseConnection[T](DbConnection dedicatedConnection, Func`2 func)
   at Hangfire.SqlServer.SqlServerConnection.GetStateData(String jobId)
   at Hangfire.Server.ServerJobCancellationToken.IsJobAborted()
   at Hangfire.Server.ServerJobCancellationToken.ThrowIfCancellationRequested()
   at <PRIVATE>
   at System.Threading.Tasks.Parallel.<>c__DisplayClass17_0`1.<ForWorker>b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.<>c__DisplayClass176_0.<ExecuteSelfReplicating>b__0(Object )
ClientConnectionId:b35b47e6-c77e-48e7-80c5-47f8a92eb047
Error Number:8525,State:1,Class:16

DisableConcurrentExecution causes PerformContext.Writeline to through an exception

I added the DisableConcurrentExecution attribute to a job where I'm doing logging, some of it async. Before adding the attribute logging was working fine. As soon as I added the attribute I started getting an exception on PerformContext.WriteLine there Exception message was

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: Connection currently has transaction enlisted.  Finish current transaction and retry. occurred

And the stack trace was:

  at System.Data.SqlClient.SqlConnection.EnlistTransaction(Transaction transaction)
   at Hangfire.SqlServer.SqlServerStorage.<>c__DisplayClass27_0`1.<UseTransaction>b__0(DbConnection connection)
   at Hangfire.SqlServer.SqlServerStorage.UseConnection[T](DbConnection dedicatedConnection, Func`2 func)
   at Hangfire.SqlServer.SqlServerStorage.UseTransaction[T](DbConnection dedicatedConnection, Func`3 func, Nullable`1 isolationLevel)
   at Hangfire.SqlServer.SqlServerStorage.UseTransaction(DbConnection dedicatedConnection, Action`2 action)
   at Hangfire.SqlServer.SqlServerWriteOnlyTransaction.Commit()
   at Hangfire.Console.Storage.ConsoleStorage.AddLine(ConsoleId consoleId, ConsoleLine line)
   at Hangfire.Console.Server.ConsoleContext.AddLine(ConsoleLine line)
   at Hangfire.Console.Server.ConsoleContext.WriteLine(String value, ConsoleTextColor color)
   at Hangfire.Console.ConsoleExtensions.WriteLine(PerformContext context, String value)

Color of console

This overload does not work.
context.WriteLine("This is a test Green message", ConsoleTextColor.Green);

Background Color does not work

I have a separate dashboard and server in two different web projects which I configured both and added

            GlobalConfiguration.Configuration
                .UseSqlServerStorage("BeaconDbCtx")
                .UseConsole(new ConsoleOptions
                     {
                         BackgroundColor = "#0d3163"
                     });

Here is the screenshot on the Dashboard

hangfire console

It can log the messages but the display seems off.

I am using these packages

  <package id="Hangfire" version="1.6.8" targetFramework="net45" />
  <package id="Hangfire.Console" version="1.2.0" targetFramework="net452" />
  <package id="Hangfire.Core" version="1.6.8" targetFramework="net45" />
  <package id="Hangfire.SqlServer" version="1.6.8" targetFramework="net45" />

Can't see logging in dashboard when using nested functions

Hi there,

I have the following code:

// Old method
public void TaskMethod()
{
    TaskMethod(arg1, arg2, null);
}

public void TaskMethod(PeformContext context)
{
     context.WriteLine("MyTask Starting");
     /// do something
     context.WriteLine("MyTask Finished");
}

If I call the following method, I do not see any output, even though the task works and I can see the output on the console window, but not on the dashboard

RecurringJob.AddOrUpdate(jobId, () => Jobs.TaskMethod(), Cron.Minutely);

If I call with null everything works as normal

RecurringJob.AddOrUpdate(jobId, () => Jobs.TaskMethod(null), Cron.Minutely);

In the documentation you mention that HangFire substitutes the null does do I have to do something differently if I don't want to pass null from my program calling code?

Wrong order of the logs

When using PerformContext.WriteLine, the logs are often in the wrong order.

console-wrong-log-order

Current Setup :

  • Hangfire 1.6.14
  • Hangfire.Console 1.3.3
  • Hangfire.Mongo 0.4.0
  • Mongo Version : 3.0.12 on Windows

It seems okay when the first log appears, however when the job is finished it gets moved to the end of the paragraph.

It used to be on any log, however I can't seem to reproduce at the moment, now it's usually the first log that changes position.

Hangfire.Console with Redis does not seems to work

Hi,

I want to use Hangfire.Console with Redis, but it does not seems to work.

I have the following configuration code:

GlobalConfiguration.Configuration
    .UseRedisStorage(RedisMultiplexer)
    .UseConsole();

The JobMethod:

public void AddLatestDocsToIndex(PerformContext context)
{
    var lastId = this.GetIdsByIndexerConfiguration(this.IndexerConfigurations["GetLastDocIdFromIndex"]).FirstOrDefault();
    var models = TransactionEntityModel.GetBiggerThanId(lastId);
    if (!models.Any())
    {
        context.WriteLine("No new documents found.");
	return;
    }
    var helper = new SearchHelper<TransactionEntityConfiguration, TransactionEntityModel>();
    helper.AddOrUpdateBulk(models);
    context.WriteLine($"Added {models.Count} document(s) to the index.");
}

And the Hangfire recurring job call:

RecurringJob.AddOrUpdate<TransactionEntityConfiguration>(
    "TransactionLatestDocsIndexer",
    x => x.AddLatestDocsToIndex(null),				
    Cron.MinuteInterval(5));

In the dashboard I don't see any Logging message. Also, when I look in Redis, the log messages don't show up anywhere.

I am using the following packages and versions:

<package id="Hangfire" version="1.6.12" targetFramework="net451" />
<package id="Hangfire.Console" version="1.3.1" targetFramework="net451" />
<package id="Hangfire.Core" version="1.6.12" targetFramework="net451" />
<package id="Hangfire.Redis.StackExchange" version="1.6.7.24" targetFramework="net451" />

Am I doing something wrong?

Can not get progress bar to display

Hello,
i am trying to use the progress bar

I have tried a couple of different ways but can not get the progress bar to every display in hangfire


 public void WriteToConsoleProgress(int val)
        {
            if (context != null)
            {
                System.Diagnostics.Debug.WriteLine("WriteToConsoleProgress=" + val);
                if (iProgressBar == null)
                {
                    iProgressBar = ConsoleExtensions.WriteProgressBar(context, "BankBillPay", (double)val, ConsoleTextColor.Cyan);
                    iProgressBar.SetValue(0);
                }
                iProgressBar.SetValue(val);
            }
        }

and this way

 public void WriteToConsoleProgress(int val)
        {
            if (context != null)
            {
                System.Diagnostics.Debug.WriteLine("WriteToConsoleProgress=" + val);
                if (iProgressBar == null)
                {
                    iProgressBar = context.WriteProgressBar();
                    iProgressBar.SetValue(0);
                }
                iProgressBar.SetValue(val);
            }
        }

I get no exceptions and no display.

thanks for any help

Count is required when enumerable is not a collection

Extension method WithProgress will throw exception is collection has no items

else if (count < 0)
Count is required when enumerable is not a collection .

You receive and IEnumerable and return an IEnumerable implementation named progress enumerable.

Instead of throwing, could you just return the enumerable parameter ?

Suggested implementation :

public static IEnumerable WithProgress(this IEnumerable enumerable, IProgressBar progressBar, int count = -1)
        {
            if (enumerable is ICollection)
            {
                count = ((ICollection)enumerable).Count;
            }
            else if (count < 0)
            {
               return enumerable;
            }

            return new ProgressEnumerable(enumerable, progressBar, count);
        }

Hangfire.Console unhandled exception crashes BackgroundJobServer

Hi,
I'm evaluating Hangfire and your cool extension, Hangfire.Console. I am experiencing what appears to be, based on the stack trace, SQL based unhandled exceptions within the Hangfire.Console.Storage.ConsoleStorage.AddLine method is taking down the Hangfire BackgroundJobServer. I don't know if there is a certain design pattern for how you use Hangfire.Console or how your run the BackgroundJobServer to make it more resilient to these types of issues.

Your feedback is appreciated.

Add Option to scroll screen with log creation

I've noticed when viewing the console for jobs that have longer logs that it is difficult/tedious to keep scrolling to keep up with log creation. It would be nice to have an option to have the page scroll automatically to keep up with the creation of the logs.

How to pass the PerformContext to services for logging?

Hello,
Thank you so much for this addition to hangfire, we could really use it where I work!

The only confusion I have is with passing this PerformContext object to the actual background jobs that are running. Is this supposed to be passed with the BackgroundJob.Enqueue(() => TaskMethod(null)) call?

Seems like I can't new one up in my service when I'm doing the background tasks as the constructor takes a lot of parameters that I wouldn't have in my service, so just need some guidance on how to inject that object into my background jobs so that I can start to see some logging in the hangfire dashboard!

Thanks again for writing this, and I hope to hear from you soon!

Brent Coney

Support for hyperlinks

Is there a way to provide a hyperlink in the console output?

Currently seems to be rendered as a literal.

Console not displaying messages

Hi,
I'm using on Hangfire console 1.3.0 with Hangfire 1.6.9, I'm using MySql storage but console is not displayed on Job Details.

My startup:

            GlobalConfiguration.Configuration
                .UseStorage(new MySqlStorage("HangFireMySqlContext"))
                .UseConsole(new ConsoleOptions { ExpireIn = TimeSpan.FromDays(30) });


            var dashboardOptions = new DashboardOptions();
            dashboardOptions.Authorization = new[] { new HangFireAuthorizationFilter() };
            app.UseHangfireDashboard("/hangfire" , dashboardOptions);
            app.UseHangfireServer(new BackgroundJobServerOptions { WorkerCount = 3 });

            HangfireServices services = new HangfireServices();
            services.StartDownload();
            services.StartParse();
            services.StartSend();

I tried to turn-off cache for all application in this way:

public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new OutputCacheAttribute { VaryByParam = "*", Duration = 0, NoStore = true, }); } }

I check the records are properly stored on "set" table in my database but I had no display on Job Details, sometimes when I reset my database and re-start deployment the first time of job execution display console but not on the next scheduled times.

Looking to Chrome Developer Tools \ Network, I can see no \hangfire\console requests

Do you have some idea to fix it ?

Console not displaying messages

I had Hangfire.Console working in a POC and I'm trying to move it into my real service code and now console messages no longer appear.

My application structure is:

Window Service hosting Hangfire server (used Topshelf to create service)
Job assembly is placed in the /bin folder (but not a direct reference from service to assembly).

The job runs correctly and I hit the break point of performingContext.WriteLine() but after the call there is no console output.

My windows service has the following Startup.cs

public class Startup
{
	public void Configuration( IAppBuilder app )
	{
		app.Use<GlobalExceptionMiddleware>();
		app.UseHangfireDashboard( "/hangfire", new DashboardOptions
		{
			Authorization = new[] { new LocalNetworkAuthorizationFilter() }
		} );
	}
}

GlobalExceptionMiddleware just dumps any errors to Trace.WriteLine and LocalNetworkAuthorizationFilter allows access to everyone on the same intranet to the dashboard.

In the service public bool Start( HostControl hostControl ) method, I have the following:

var sqlServerOptions = new SqlServerStorageOptions
{
	QueuePollInterval = TimeSpan.FromSeconds( ServiceSettings.Current.PollingSeconds )
};

GlobalConfiguration
	.Configuration
		.UseSqlServerStorage( hangfireConnection, sqlServerOptions )
		.UseConsole();

GlobalJobFilters.Filters.Add( new AutomaticRetryAttribute { Attempts = 0 } );
GlobalJobFilters.Filters.Add( new EmailOnErrorFilter() );

As far as I can determine, this is 'exact' same setup I had in my POC. Can you spot any reason why the console wouldn't be working?

Thanks.

Urls with query string not parsed correctly for the console

I am attempting to write a Url to the console using
context.WriteLine("http://myhost/api?param1=abc&param2=xyz")

but in the console the html rendered is
<a target="_blank" rel="nofollow" href="http://myhost/api?param1=abc&amp;">http://myhost/api?param1=abc&amp;</a>;param2=xyz

I believe this has to do with ConsoleRender line 92 doing an HtmlEncode before detecting links

Using with ASP.NET

Not able to get console to display with following:

        app.UseHangfireDashboard("", new DashboardOptions
        {

            Authorization = new[] {new HangfireNoAuthorizationFilter()},

        });
      GlobalConfiguration.Configuration
            .UseSqlServerStorage("nectstring", options)
            .UseConsole(consoleOptions);

Using ASP.NET (not core) and not making a call to app.UseHangfireServer

Any help?? Thanks!

Style not working on Chrome (Version 57.0.2987.133 (64-bit))

Style works on IE and Firefox but when I see the site on chrome it shows as:
image

I dont think this is right.

I must add that I checked and there are no errors in the Chrome console. Doing quick inspect tells that some CSS styles are not applied in chrome for example margin-right: 20px on the span where time is displayed.

liblog?

this is really a wonderful addition to hangfire. great work!
maybe it makes sense to also write the log entries to liblog. so they appear in our normal logs too.

Logging double, until refresh

Haai,

So i'm using Hangfire.Console, and while keeping the page open looking at the realtime updates (amazing) - it's logging all entries twice for some reason. see below:

image

If I refresh the page, the doubles are gone - so it only happens for new entries whilst I keep the page open.

This is the logging call:


            // set color according to "level"
            context.SetTextColor(
                // warning
                level == LogLevel.Warning 
                    ? ConsoleTextColor.DarkYellow 
                    // error OR critical
                    : level == LogLevel.Error || level == LogLevel.Critical 
                        ? ConsoleTextColor.Red 
                        // Trace
                        : level == LogLevel.Trace 
                            ? ConsoleTextColor.Gray 
                            // Info/Debug
                            : ConsoleTextColor.White
            );

            context.WriteLine($"{msg}");
            context.ResetTextColor();

Any ideas if this is a bug or an issue on my side?

Progress bar not showing

I have problem with progress bar .I set _progress = context.WriteProgressBar("Test",50, ConsoleTextColor.Blue);
but not showing
image
Can you advise me?
I am trying how write in the documentation but not showing

I use last version Hangfire

This is bug in the Google Chrome in the Edge is working

Problem was in the cache

Progress bar enhancement

Many times when using a progress bar, we are in a for-each loop.
Looks something like this:

int pos=0;
int max=6200;
var bar=PerformContext.WriteProgressBar();
foreach (var item in collection)
{
   SomeWork();
   pos++
   bar.SetPos(pos/max*100);
}

Given that is such a common pattern, perhaps a simple enhancement would have it also work like this:

var bar=PerformContext.WriteProgressBar(6200);  (pass in the max)
foreach (var item in collection)
{
   SomeWork();
   bar.IncRelativePos();
}

Where the progress bar instance maintains the state, etc. ( Additionally, this would enable a feature where the progress bar shows est time remaining instead of % complete - since it could track how long it has been and has all other info needed)

See console on failed jobs

When a hangfire job fails it gets placed in the 'Failed' job group.
If you go to that failed job and click it for details, it shows you the exception information.

It would be great if it would also show the output from the console that happened too!

Is that possible?

WriteLine using ElectStateContext ?

Is there a way to access the ConsoleContext from the OnStateElection method of a JobFilterAttribute?

I'd like to log to the Console actions taken when a job failed, for retrospective purposes, so that I can view the actions in the Hangfire Dashboard Console.

I appreciate any help you can provide!

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.