Serilog console conditional output template based on log level, (and low profile color in console) - configure

Please first excuse me, I am not so familiar with the Serilog, I started with it quite recently.
I would like use a certain log level in my console app to be used as normal console output by default (output just the rendered message) and then optionally, when specified by optional commandline argument like -verb also have output in such default format "{Timestamp:HH:mm:ss} [{Level:u3}] {Message}{NewLine}{Exception}"(and additionally perhaps with more low profile color)
My questions are:
which (the cleanest) way can it be accomplished?
a) in case of filtering: can you please help me, how the filtering would look like in the fluent configuration API?
b) in case of using a custom ITextFormater, can it somehow inherit the part
providing rendering such format templates as mentioned above?
c) any better way, or ??
is it possible to somehow make (using the output format template) for the console sink such a "lower profile" color?

You can just switch the outputTemplate based on the presence of the command-line flag:
bool verbose = false;
var template = verbose ?
"{Timestamp:HH:mm:ss} [{Level:u3}] {Message}{NewLine}{Exception}" :
"{Message}{NewLine}";
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(outputTemplate: template,
theme: SystemConsoleTheme.Grayscale)
.CreateLogger();
See the theme argument supplied in the example for how to change coloring.

Related

discordpy 2.0 interaction is a required argument that is missing

#client.command(brief="Send a message with a button!")
async def button(ctx,interaction: discord.Interaction):
view = discord.ui.View()
style = discord.ButtonStyle.gray
item = discord.ui.Button(style=style, label="Read the docs!", url="https://discordpy.readthedocs.io/en/master")
view.add_item(item=item)
await interaction.response.send_message("This message has buttons!", view=view)
await interaction.response.send_message(content="Hi", ephemeral=True)
discord.ext.commands.errors.MissingRequiredArgument: interaction is a required argument that is missing.
Actually i just want to send a message by intraction, but seem itwasn't work :(
I think you are confused about the basic concepts since your code is mixed up command and interaction stuffs.
If you want to create button, you cannot write in the older command way like #client.command. You need to either use application command or hybrid command (which is a mix of interaction and command)
So, you should never have something like (ctx: Context, interaction: Interaction) together.
Also, classically, you need to create a view class and create a button inside this view class. Then you can attach this view to your message or embed when you send this to the user.
And, if you want to respond to user multiple times in a application command, you cannot do that through interaction.response (only once). You can use interaction.followup() for later responses. link
For view examples, see file example under this
For slash command (application command) example, see this

How to use querycommands in CKEditor

In TinyMCE i am able to get the currently selected values by using queryCommandValue and queryCommandState like this:
tinymce.activeEditor.queryCommandValue("FontName");
This would get me the selected fontname. How would i do something like this in CKEditor?
The command state can be checked using the following available methods in CKEDITOR.command list.
previousState
Indicates the previous command state.
alert( command.previousState );
state
Indicates the editor state. Possible values are:
CKEDITOR.TRISTATE_DISABLED: the command is disabled. It's execution will have no effect. Same as disable.
CKEDITOR.TRISTATE_ON: the command is enabled and currently active in the editor (for context sensitive commands, for example).
CKEDITOR.TRISTATE_OFF: the command is enabled and currently inactive in the editor (for context sensitive commands, for example).
Do not set this property directly, this can also be achieved using the #setState method instead.
e.g
command.setState( CKEDITOR.TRISTATE_ON );
one can also check the state to do execute a command or to do some task
if ( command.state == CKEDITOR.TRISTATE_DISABLED )
alert( 'This command is disabled' );
queryCommandValue can be done while executing a normal command like command.exec(data) and this value of data should come from some variable in which this value is stored.
You can get the document to perform direct DOM calls as you want by doing it this way
CKEDITOR.instances.editor1.document.$.queryCommandValue("FontName")
but I must warn you that directly calling the DOM instead of using the CKEditor API is gonna be harder. CKEditor has been designed to wrap the differences between browsers, and if you want to skip that and use other API then you'll have to redo a lot of work.

How to Program xulrunner application to display output file or command line?

My question is in response to this article
https://developer.mozilla.org/En/How_to_check_the_security_state_of_an_XMLHTTPRequest_over_SSL
I have downloaded and configured the xulrunner the only problem I'm getting to run javascript given in the link to display it output. Using xulrunner i want to know how can i produce an output as a headerless command-line program not gui.
var httpRequest = Components.classes["#mozilla.org/xmlextr/xmlhttprequest;1"].createInstance();
// Disable alert popups on SSL error
httpRequest.mozBackgroundRequest = true;
httpRequest.open("GET", "https://developer.mozilla.org/", true);
httpRequest.onreadystatechange = function (aEvt) {
if (httpRequest.readyState == 4) {
// Print security state of request
dumpSecurityInfo(httpRequest.channel);
}
};
httpRequest.send(null);
In the above code taken from the same link i want to see the output of function on my command screen or even a writing the information to file would do.
Do i have to change something in *.xul file extension.? I'm new to using xulrunner some help would be very helpful for me.
To print something to the console you use the dump() function. If your code runs in the context of a window you will need to change browser.dom.window.dump.enabled preference to true. XPCOM components can simply call dump() without changing this preference.

Logging an onFailure inError in WebOS

An onFailure handler in webOS has an argument inError. I tried printing it using: console.log("error: " + inError);, but the result is only: error: [object Object]*** (app/assistants/main-assistant.js:26), which isn't much use. How can I log something more useful instead?
Update:
Ares generates: alarm1Failure: function(inSender, inError) {}. However, the error is contained as the errorText property of the first object and the second object is the request
I would use the interactive debugger at:
http://ares.palm.com/AresDebug/
Connect your device and run your app. Put your app name in the 'Script Filter' box and click get scripts.
Now use the 'Available Scripts' pull down to find your assembly.
You can set breakpoints (click on line numbers to the left) and inspect variables using the lower left pane and '>' prompt.
Be sure to use Chrome or Safari as it will not work with IE.
There is also a logger at:
http://ares.palm.com/AresLog/
if you don't want to use the debugger, then you probably should know something about the inError object getting returned to you. In this case I assume the onFailure comes from a Protocol function's callback, so try looking in the Protocol documentation to see what information the error object should contain.
Also for any logging purposes don't forget about the imensely useful function
JSON.stringify(obj)
It will take an object and return a JSON representation that you can log so you can see all the properties at once.

Copy object values in Visual Studio debug mode

In Visual Studio debug mode it's possible to hover over variables to show their value and then right-click to "Copy", "Copy Expression" or "Copy Value".
In case the variable is an object and not just a basic type, there's a + sign to expand and explore the object. It there a way to copy all that into the clipboard?
In the immediate window, type
?name_of_variable
This will print out everything, and you can manually copy that anywhere you want, or use the immediate window's logging features to automatically write it to a file.
UPDATE: I assume you were asking how to copy/paste the nested structure of the values so that you could either search it textually, or so that you can save it on the side and then later compare the object's state to it. If I'm right, you might want to check out the commercial extension to Visual Studio that I created, called OzCode, which lets you do these thing much more easily through the "Search" and "Compare" features.
UPDATE 2 To answer #ppumkin's question, our new EAP has a new Export feature allows users to Export the variable values to Json, XML, Excel, or C# code.
Full disclosure: I'm the co-creator of the tool I described here.
You can run below code in immediate window and it will export to an xml file the serialized XML representation of an object:
(new System.Xml.Serialization.XmlSerializer(obj.GetType())).Serialize(new System.IO.StreamWriter(#"c:\temp\text.xml"), obj)
Source: Visual Studio how to serialize object from debugger
Most popular answer from https://stackoverflow.com/a/23362097/2680660:
With any luck you have Json.Net in you appdomain already. In which
case pop this into your Immediate window:
Newtonsoft.Json.JsonConvert.SerializeObject(someVariable)
Edit: With .NET Core 3.0, the following works too:
System.Text.Json.JsonSerializer.Serialize(someVariable)
There is a extension called Object Exporter that does this conveniently.
http://www.omarelabd.net/exporting-objects-from-the-visual-studio-debugger/
Extension: https://visualstudiogallery.msdn.microsoft.com/c6a21c68-f815-4895-999f-cd0885d8774f
You can add a watch for that object, and in the watch window, expand and select everything you want to copy and then copy it.
By using attributes to decorate your classes and methods you can have a specific value from your object display during debugging with the DebuggerDisplay attribute e.g.
[DebuggerDisplay("Person - {Name} is {Age} years old")]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
I always use:
string myJsonString = JsonConvert.SerializeObject(<some object>);
Then I copy the string value which unfortunately also copies the back slashes.
To remove the backlashes go here:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace
Then within the <p id="demo">Visit Microsoft!</p> element replace the text with the text you copied.
then replace the var res = str.replace("Microsoft", "W3Schools"); line with
var res = str.replace(/\\/g, '')
Run these new changes but don't forget to click the "try it" button on the right.
Now you should have all the text of the object in json format that you can drop in a json formatter like http://jsonformatter.org or to create a POCO you can now use http://json2csharp.com/
ObjectDumper.NET
This is an awesome way!
You probably need this data for a unit test, so create a Sandbox.cs temporary test or you can create a Console App.
Make sure to get NuGet package, ObjectDumper.NET, not ObjectDumper.
Run this test (or console app)
View test output or text file to get the C# initializer code!
Code:
[TestClass]
public class Sandbox
{
[TestMethod]
public void GetInitializerCode()
{
var db = TestServices.GetDbContext();
var list = db.MyObjects.ToList();
var literal = ObjectDumper.Dump(list, new DumpOptions
{
DumpStyle = DumpStyle.CSharp,
IndentSize = 4
});
Console.WriteLine(literal); // Some test runners will truncate this, so use the file in that case.
File.WriteAllText(#"C:\temp\dump.txt", literal);
}
}
I used to use Object Exporter, but it is 5 years old and no longer supported in Visual Studio. It seems like Visual Studio Extensions come and go, but let's hope this NuGet package is here to stay! (Also it is actively maintained as of this writing.)
Google led me to this 8-year-old question and I ended up using ObjectDumper to achieve something very similar to copy-pasting debugger data. It was a breeze.
I know the question asked specifically about information from the debugger, but ObjectDumper gives information that is basically the same. I'm assuming those who google this question are like me and just need the data for debugging purposes and don't care whether it technically comes from the debugger or not.
I know I'm a bit late to the party, but I wrote a JSON implementation for serializing an object, if you prefer to have JSON output. Uses Newtonsoft.Json reference.
private static void WriteDebugJSON (dynamic obj, string filePath)
{
using (StreamWriter d = new StreamWriter(filePath))
{
d.Write(JsonConvert.SerializeObject(obj));
}
}
I've just right clicked on the variable and selected AddWatch, that's bring up watch window that consists of all the values. I selected all and paste it in a text a text editor, that's all.
Object Dumper is a free and open source extension for Visual Studio and Visual Studio Code.
"Dump as" commands are available via context menu in the Code and Immediate windows.
It's exporting objects to:
C# object initialization code,
JSON,
Visual Basic object initialization code,
XML,
YAML.
I believe that combined with the Diff tool it can be helpful.
I'm the author of this tool.
if you have a list and you want to find a specific variable:
In the immediate window, type
myList.Any(s => s.ID == 5062);
if this returns true
var myDebugVar = myList.FirstOrDefault(s => s.ID == 5062);
?myDebugVar
useful tips here, I'll add my preference for when i next end up here asking this question again in the future.
if you don't mind adding an extension that doesn't require output files or such there's the Hex Visualizer extension for visual studio, by mladen mihajlovic, he's done versions since 2015.
provides a nice display of the array via the usual magnifine glass view object from the local variables window.
https://marketplace.visualstudio.com/items?itemName=Mika76.HexVisualizer2019 is the 2019 version.
If you're in debug mode, you can copy any variable by writing copy() in the debug terminal.
This works with nested objects and also removes truncation and copies the complete value.
Tip: you can right click a variable, and click Copy as Expression and then paste that in the copy-function.
System.IO.File.WriteAllText("b.json", page.DebugInfo().ToJson())
Works great to avoid to deal with string debug format " for quote.
As #OmerRaviv says, you can go to Debug → Windows → Immediate where you can type:
myVariable
(as #bombek pointed out in the comments you don't need the question mark) although as some have found this limits to 100 lines.
I found a better way was to right click the variable → Add Watch, then press the + for anything I wanted to expand, then used #GeneWhitaker's solution, which is Ctrl+A, then copy Ctrl+C and paste into a text editor Ctrl+V.

Resources