Custom date format with NLog - nlog

It appears to me as tho the in-built date formats in NLog do not include the timezone correctly. We need to log UTC time WITH the trailing Z so that Splunk knows what the local time is, eg:
{date:universalTime=true:format=yyyy-MM-dd HH:mm:ss.ffffZ}
This produces the correct dates we need.
Rather than inserting this in all our configs across multiple apps, I'd prefer to define a variable that will do this, eg:
{ourdate}
I've had a hack around but I cant figure out how to do this. Is it possible?
Thanks
PS. {longdate} does include the timezone but it drops the milliseconds.

The easiest thing for you to do is probably to just bite bullet and use the regular NLog DateLayoutRenderer and specify the configuration values in every config file. If you'd rather keep your config files simple, you could write your own date LayoutRenderer that generates the date in a specific format.
Here is a rough implementation (not tested). It will always log the date in the format that you specified above. I based it on NLog's DateLayoutRenderer, the source of which you can find here:
https://github.com/NLog/NLog/tree/master/src/NLog/LayoutRenderers
You don't really need more options, because you can easily achieve the format you want using the built in DateLayoutRenderer. This implementation just saves you some effort in your NLog.config file(s).
namespace NLog.LayoutRenderers
{
using System.ComponentModel;
using System.Text;
using NLog.Config;
/// <summary>
/// Current date and time.
/// </summary>
[LayoutRenderer("utczdate")]
[ThreadAgnostic]
public class UTCZDateLayoutRenderer : LayoutRenderer
{
/// <summary>
/// Initializes a new instance of the <see cref="UTCZDateLayoutRenderer" /> class.
/// </summary>
public UTCZDateLayoutRenderer()
{
}
/// <summary>
/// Renders the current date and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var ts = logEvent.TimeStamp;
builder.Append(ts.ToString("yyyy-MM-dd HH:mm:ss.ffffZ", CultureInfo.InvariantCulture));
}
}
}
You can use this in your NLog.config file like this:
{utczdate}
Good luck!

Use ${date:universalTime=true:format=o}
Format 2015-11-06T14:24:52.4025753Z ISO 8601
You are wanting the Round-Trip ("O","o") Format Specifier
The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601.

Related

how to register a keystore extension in substrate benchmarking?

I'm writing benchmark for a pallet, in which I need to generate key pairs as input. However with --features runtime-benchmarking, I seems not able to use full-crypto and sp_core::Pair.
So the only way I found is to use RuntimeAppPublic::generate_pair, but it needs a keystore registered for the ext. But with benchmark! macro I wasn't able to do this.
So are there any suggestions? Either on generating keypairs without std or registering a keystore extension within the benchmark! framework.
Edit: I found something may be helpful in the doc.
/// You can construct benchmark by using the `impl_benchmark_test_suite` macro or
/// by manually implementing them like so:
///
/// ```ignore
/// #[test]
/// fn test_benchmarks() {
/// new_test_ext().execute_with(|| {
/// assert_ok!(Pallet::<Test>::test_benchmark_dummy());
/// ...
/// });
/// }
/// ```
From this doc, I think we can manipulate the test_ext easily for the test. But there are no information about the bench_xxx functions. As far as I can see in the cargo expand file, it maybe a bit different for benchmark.
It's about genesis config, closing.

VLC libvlc_state_t State Machine?

Does anyone know if the VLC project has a defined state machine for the libvlc_state_t states? The state machine states are exposed via libvlc and then again via bindings into other languages (for example, LibVLCSharp). The enum is documented here, but I can't find a description of transitions or other details.
Update
I'd like to see this get rolled into VLC docs at some point. While the state machine might seem obvious, I am encountering small oddities like the Buffering event getting called but the Media not seeming to pass through the Buffering state - it's still in the Playing state.
These little things add up and it would probably help improve developer experience to get them added. What I'm looking for as a solution is a typical state machine that includes at a minimum the states, the transitions, and notes about which events are actually fired on which transitions (and if they happen before or after the state actually changes). Anything around threading concerns (e.g. sync vs. async transitions) and allowable actions while in a given state are a bonus.
I did some work to capture the observed behavior. This is incomplete and imperfect, but perhaps it may help others as they build on top of libvlc/LibVLCSharp (I was on v3.5.1, VideoLAN.LibVLC.Windows v3.0.14). The dashed arrows pointing to the right are to show when certain events fire. Note that some of these behaviors are potentially specific to the type of media or the fact that reading is occurring through the MediaInput interface, so your mileage may vary.
A few notes:
Things did not seem to always work properly if you tried to e.g. seek while the media was Opening. For example, I saw .Time and .Position fall permanently out of sync. I strongly recommend waiting until after a Play() operation before doing much.
The Buffering state was not seen to be in use, but the Buffering event would fire at least the Opening and Playing states.
As others have noted, you can't simply call Play() once the media ends. You need to Stop() after EndReached fires, and - as with many of the callbacks - you need to make sure you handle this in a non-deadlocking way. It can and will silently deadlock. Even using Dispatcher may choose to run on the same thread, so you have to guarantee a separate thread. So far I've had good luck with e.g. ThreadPool.QueueUserWorkItem(_ => yourMediaPlayer.Stop()); You can then hook Stopped to trigger further behavior like Play().
I'm still not sure the exact behavior around ErrorEncountered and recovery to Play() again; it wasn't easy to trigger this behavior.
Ultimately this state machine allowed me to build one on top of it to handle behaviors like "make the file playable again when the end is reached".
Thanks #mfkl and many others for the hard work - with a bit of digging this has been a great library to build on!
media.State
Should give you what you want.
The libvlc_state_t C enum is simply defined as a C# enum in libvlcsharp, like so:
/// <summary>Note the order of libvlc_state_t enum must match exactly the order of</summary>
/// <remarks>
/// <para>mediacontrol_PlayerStatus,</para>
/// <para>input_state_e enums,</para>
/// <para>and VideoLAN.LibVLCSharp.State (at bindings/cil/src/media.cs).</para>
/// <para>Expected states by web plugins are:</para>
/// <para>IDLE/CLOSE=0, OPENING=1, PLAYING=3, PAUSED=4,</para>
/// <para>STOPPING=5, ENDED=6, ERROR=7</para>
/// </remarks>
public enum VLCState
{
/// <summary>
/// Nothing special happening
/// </summary>
NothingSpecial = 0,
/// <summary>
/// Opening media
/// </summary>
Opening = 1,
/// <summary>
/// Buffering media
/// </summary>
Buffering = 2,
/// <summary>
/// Playing media
/// </summary>
Playing = 3,
/// <summary>
/// Paused media
/// </summary>
Paused = 4,
/// <summary>
/// Stopped media
/// </summary>
Stopped = 5,
/// <summary>
/// Ended media
/// </summary>
Ended = 6,
/// <summary>
/// Error media
/// </summary>
Error = 7
}
You can also subscribe to the StateChanged event on the Media to get notified of changes in the State status.

How to create a ReSharper 8.X Custom Macro that can fetch and process the containing type name

ReSharper 8.X ships with a macro that fetches the "Containing Type Name", but what I want to do is manipulate that name. I'm using this in a Visual Studio 2013 Web API project, and I want a template that takes the class name and builds the URL that has to be called. So, for example, suppose I have this:
public class AnnouncementController : ApiController
{
//Want to put a template here!
[HttpGet]
public HttpResponseMessage GetActiveAnnouncements()
{
/// ...
}
}
now my ReSharper template will look something like this:
/// This sample shows how to call the <see cref="$METHOD$"/> method of controller $CLASS$ using the Web API.
/// https://myurl.mydomain.com/api/$CONTROLLER$/$METHOD$
$Controller$, by convention, is the class name minus the letters 'Controller'. This is because ASP.NET MVC Web API projects expect classes derived from ApiController to end with the string 'Controller',
Since this class is AnnouncementController, the template should output
https://myurl.mydomain.com/api/Announcement/GetActiveAnnouncements
Resharper's Built-In Macros can give me some of what I need, but I want to write a custom macro that fetches the containing type name and chops "Controller" off of it. I would like to do that directly, without storing the containing type name in another parameter.
Also, how do I install this custom macro? I've Googled around, and all I found was a lot of dead links and old walkthroughs written for ReSharper version 7 and below that do NOT work with ReSharper 8.x
After a lot of fighting, here is my solution.
[MacroImplementation(Definition = typeof (ControllerNameMacroDefinition))]
public class ControllerNameMacroImplementation : SimpleMacroImplementation
{
public ControllerNameMacroImplementation([Optional] IReadOnlyCollection<IMacroParameterValueNew> arguments)
{
}
public override HotspotItems GetLookupItems(IHotspotContext context)
{
var ret = "CONTROLLER";
var fileName = GetFileName(context);
if (!fileName.IsNullOrEmpty())
{
//Replace "Controller.cs" in two separate steps in case the extension is absent
ret = fileName.Replace("Controller", "").Replace(".cs", "");
}
return MacroUtil.SimpleEvaluateResult(ret);
}
/// <summary>
/// Returns the filename of the current hotspot context
/// </summary>
private string GetFileName(IHotspotContext context)
{
var psiSourceFile = context.ExpressionRange.Document.GetPsiSourceFile(context.SessionContext.Solution);
return psiSourceFile == null ? string.Empty : psiSourceFile.Name;
}
}
I wanted to do exactly this, but for JavaScript Jasmine tests -- SomethingViewModel.js, with a fixture of SomethingViewModelFixture.js, but wanted to be able to refer to SomethingViewModel in the file. A few slight modifications to the above made it possible.
Unfortunately, there's a ton more things you need to do in order to get your plugin to actually install. Here's a list. I hope it's comprehensive.
NuGet package install JetBrains.ReSharper.SDK, make sure you have the correct version installed!
Copy your Class Library DLL to C:\Users\<you>\AppData\Local\JetBrains\ReSharper\<version>\plugins\<your plugin name>, creating the plugins directory if needed.
You need the plugin Annotations in your AssemblyInfo.cs file:
[assembly: PluginTitle("Your extensions for ReSharper")]
[assembly: PluginDescription("Some description")] -- this is displayed in ReSharper->Options->Plugins
[assembly: PluginVendor("You")]
You need a class in your project that defines the MacroDefinition, as well as the above MacroImplementation
[MacroDefinition("MyNamespace.MyClassName", ShortDescription = "A short description of what it does.", LongDescription = "A long description of what it does.")]
"ShortDescription" - this is displayed in the "Choose Macro" dialog list.
"LongDescription" you'd think this would be in the "Choose Macro" description, but it isn't.
I just added this annotation to the above file.
The file you add the MacroDefinition to needs to implement IMacroDefinition, which has a method (GetPlaceholder) and a property (Parameters) on it. The former can return any string ("a") and the latter can return an empty array.
You can ignore the WiX/NuGet stuff if you want. Just for a local install.
In VS, the ReSharper->Options->Plugins section has some troubleshooting details on why your plugin might not be loading.
Good luck!

CruseControl.Net mail check-in

How can I configure the "publisher" section in ccnet.config file in order to send email only to person who checked-in when the build fails?
Thanks,
John.
I don't think you can "out of the box".
You'll have to write your own publisher...and piggy back on "FailureUsers".
https://github.com/ccnet/CruiseControl.NET/blob/master/project/core/IIntegrationResult.cs
// Users who contributed modifications to a series of failing builds:
/// <summary>
/// Gets the failure users.
/// </summary>
/// <value></value>
/// <remarks></remarks>
ArrayList FailureUsers { get; } // This should really be a Set but sets are not available in .NET 1.1
Here is the tech-spec:
http://confluence.public.thoughtworks.org/display/CCNET/Custom+Builder+Plug-in
Here is an example of someone who wrote one....
http://krisselden.com/2007/01/29/adding-a-custom-cruisecontrolnet-publisher/

Create file template with generic macro

this is my template code:
using System;
using System.Runtime.Serialization;
using Nethos.Ferramentas.AtributosValidacao.Numeros;
using Nethos.Ferramentas.AtributosValidacao.Textos;
$HEADER$namespace $NAMESPACE$
{
/// <summary>
/// Classe responsável pela persistência dos dados.
/// Tabela: $CLASS$s (PK: Id)
/// </summary>
[DataContract]
[KnownType(typeof(NHibernate.Collection.Generic.PersistentGenericBag< $CLASS$ >))]
[KnownType(typeof(NHibernate.Collection.PersistentBag))]
[Serializable]
public class $CLASS$
{
$END$
}
}
but in the line "[KnownType(typeof(NHibernate.Collection.Generic.PersistentGenericBag< $CLASS$ >))]" not appear name of the class, just the letter "a"... what's the problem with my code template?
I suspect this is an issue that the original 8.0 release of ReSharper has with certain plugins, under certain conditions. If you open Visual Studio by double clicking a solution file, the plugin would get initialised too late, and cause exceptions (you can verify by running "devenv.exe /ReSharper.Internal" and look for exceptions). The exceptions can interfere with various parts of ReSharper, unfortunately, macros is one that I've seen.
This has been fixed with ReSharper 8.0.1. Please can you update and try again?

Resources