- Console log formatting
- Register formatter
- Simple
- Systemd
- Set formatter with configuration
- Implement a custom formatter
- Implement custom color formatting
- Вызов консоли в WinForm приложении
- Решение
- Решение
- Как отобразить вывод/окно консоли в приложении forms?
- 9 ответов:
- Как в C# Windows Form вывести консоль внутри исполняемой программы?
- how to run a winform from console application?
- 10 Answers 10
Console log formatting
In .NET 5, support for custom formatting was added to console logs in the Microsoft.Extensions.Logging.Console namespace. There are three predefined formatting options available: Simple , Systemd , and Json .
Previously, the ConsoleLoggerFormat enum allowed for selecting the desired log format, either human readable which was the Default , or single line which is also known as Systemd . However, these were not customizable, and are now deprecated.
In this article, you will learn about console log formatters. The sample source code demonstrates how to:
- Register a new formatter
- Select a registered formatter to use
- Either through code, or configuration
- Implement a custom formatter
- Update configuration via IOptionsMonitor
- Enable custom color formatting
Register formatter
The Console logging provider has several predefined formatters, and exposes the ability to author your own custom formatter. To register any of the available formatters, use the corresponding Add
Available types | Method to register type |
---|---|
ConsoleFormatterNames.Json | ConsoleLoggerExtensions.AddJsonConsole |
ConsoleFormatterNames.Simple | ConsoleLoggerExtensions.AddSimpleConsole |
ConsoleFormatterNames.Systemd | ConsoleLoggerExtensions.AddSystemdConsole |
Simple
To use the Simple console formatter, register it with AddSimpleConsole :
In the preceding sample source code, the ConsoleFormatterNames.Simple formatter was registered. It provides logs with the ability to not only wrap information such as time and log level in each log message, but also allows for ANSI color embedding and indentation of messages.
Systemd
- Uses the «Syslog» log level format and severities
- Does not format messages with colors
- Always logs messages in a single line
This is commonly useful for containers, which often make use of Systemd console logging. With .NET 5, the Simple console logger also enables a compact version that logs in a single line, and also allows for disabling colors as shown in an earlier sample.
To write logs in a JSON format, the Json console formatter is used. The sample source code shows how an ASP.NET Core app might register it. Using the webapp template, create a new ASP.NET Core app with the dotnet new command:
When running the app, using the template code, you get the default log format below:
By default, the Simple console log formatter is selected with default configuration. You change this by calling AddJsonConsole in the Program.cs:
Run the app again, with the above change, the log message is now formatted as JSON:
The Json console formatter, by default, logs each message in a single line. In order to make it more readable while configuring the formatter, set JsonWriterOptions.Indented to true .
Set formatter with configuration
The previous samples have shown how to register a formatter programmatically. Alternatively, this can be done with configuration. Consider the previous web application sample source code, if you update the appsettings.json file rather than calling ConfigureLogging in the Program.cs file, you could get the same outcome. The updated appsettings.json file would configure the formatter as follows:
The two key values that need to be set are «FormatterName» and «FormatterOptions» . If a formatter with the value set for «FormatterName» is already registered, that formatter is selected, and its properties can be configured as long as they are provided as a key inside the «FormatterOptions» node. The predefined formatter names are reserved under ConsoleFormatterNames:
Implement a custom formatter
To implement a custom formatter, you need to:
Create an extension method to handle this for you:
The CustomOptions are defined as follows:
In the preceding code, the options are a subclass of ConsoleFormatterOptions.
The AddConsoleFormatter API:
- Registers a subclass of ConsoleFormatter
- Handles configuration:
- Uses a change token to synchronize updates, based on the options pattern, and the IOptionsMonitor interface
Define a CustomerFormatter subclass of ConsoleFormatter :
The preceding CustomFormatter.Write API dictates what text gets wrapped around each log message. A standard ConsoleFormatter should be able to wrap around scopes, time stamps, and severity level of logs at a minimum. Additionally, you can encode ANSI colors in the log messages, and provide desired indentations as well. The implementation of the CustomFormatter.Write lacks these capabilities.
For inspiration on further customizing formatting, see the existing implementations in the Microsoft.Extensions.Logging.Console namespace:
Implement custom color formatting
In order to properly enable color capabilities in your custom logging formatter, you can extend the SimpleConsoleFormatterOptions as it has a SimpleConsoleFormatterOptions.ColorBehavior property that can be useful for enabling colors in logs.
Create a CustomColorOptions that derives from SimpleConsoleFormatterOptions :
Next, write some extension methods in a TextWriterExtensions class that allow for conveniently embedding ANSI coded colors within formatted log messages:
A custom color formatter that handles applying custom colors could be defined as follows:
When you run the application, the logs will show the CustomPrefix message in the color green when FormatterOptions.ColorBehavior is Enabled .
When LoggerColorBehavior is Disabled , log messages do not interpret embedded ANSI color codes within log messages. Instead, they output the raw message. For example, consider the following:
This would output the verbatim string, and it is not colorized.
Вызов консоли в WinForm приложении
Как переделать с консоли на WinForm?
Первое слово в строке перевести в верхний регистр(большие буквы), как это реализовать в WinForm .
Вызов форм из консоли
Здравствуйте, уже неделю пытаюсь решить задачу, но пока результатов мало.. Задание: вызвать из.
Вызов консоли с winforms
мне нужно ввести несколько параметров с консоли в проекте winforms, но после первого ввода выдает.
Вызов из консоли системы
Добрый день всем. Скажу сразу — я любитель. C# — мое хобби что ли. Вопрос: Есть форма.
конечно реально. Какую именно консоль?
если просто консольное приложение надо:
Обычную консоль, как в консольном приложении.
Например ,что-бы считать данные можно было так :
как вызвать я написал, а как обеспечить синхронизацию ,сам придумай. Варианты есть разные.
Можешь через временный фаил.
Вот ещё почитай, хотя там тоже самое что я написал.
Запуск консольного приложения из WindowsForm
или ты как объект(класс объявить) хочешь в винформсе создать консль?
Именно это и хочу .
Идея в следующем :
Есть основная форма . В определенный момент она должна открыть консоль и считать оттуда введенные данные .
Решение
Решение
Спасибо огромное ,именно то что нужно было.
В Шилдте или Троелсене такого вроде нет.
И вопрос — когда создается консольное приложение то тоже импортируется эта библиотека?
Тематические курсы и обучение профессиям онлайн Профессия С#-разработчик (Skillbox) Архитектор ПО (Skillbox) Профессия Тестировщик (Skillbox) |
где вы инфу по таким вещам берете? Имею в виду:
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Вызов winform из unity
Как из юнити приложения вызвать винформ? просто подключить using System.Windows.Forms; а затем.
Вывод консоли в оконном приложении
Мне нужно затестировать как работает функция, т.е. выводить каждую операцию. Что — то.
Вызов функции в .NET-приложении
Нужно решить не особо сложную задачу из умножения матриц. Решил использовать для этой цели matlab.
Вызов действия в стороннем приложении
можно ли как-то вызвать действие чтобы файл его выполил?
Как отобразить вывод/окно консоли в приложении forms?
застрять сразу, очень простой пример:
если я скомпилирую это с параметрами по умолчанию (используя csc в командной строке), как и ожидалось, он будет компилироваться в консольное приложение. Кроме того, потому что я импортировал System.Windows.Forms , Он также покажет окно сообщения.
теперь, если я использую опцию /target:winexe Я думаю, что это то же самое, что Windows Application из параметров проекта, как и ожидалось, я буду видеть только окно сообщения и не выводить консоль.
(In факт, в тот момент, когда он запускается из командной строки, я могу выдать следующую команду, прежде чем приложение даже завершится).
Итак, мой вопрос — я знаю, что вы можете иметь вывод «windows»/forms из консольного приложения, но есть ли в любом случае, чтобы показать консоль из приложения Windows?
9 ответов:
создать проект Windows Form.
Затем: Свойства Проекта — > Приложение — > Тип Вывода — > Консольное Приложение
тогда может иметь консоль и формы, работающие вместе, работает для меня
Если вы не беспокоитесь об открытии консоли по команде, вы можете перейти в свойства для вашего проекта и изменить его на консольное приложение
Это будет по-прежнему показывать вашу форму, а также выскакивает окно консоли. Вы не можете закрыть окно консоли, но он работает как отличный временный регистратор для отладки.
просто не забудьте выключить его перед развертыванием программы.
можно назвать AttachConsole использование pinvoke для подключения окна консоли к проекту WinForms:http://www.csharp411.com/console-output-from-winforms-application/
вы также можете рассмотреть Log4net ( http://logging.apache.org/log4net/index.html) для настройки вывода журнала в различных конфигурациях.
это сработало для меня, чтобы передать вывод в файл. Вызовите консоль с помощью
cmd /c «C:\path\to\your\application.exe » > myfile.txt
добавьте этот код в приложение.
есть в основном две вещи, которые могут произойти здесь.
вывод на консоль Программа winforms может присоединяться к создавшему ее консольному окну (или к другому консольному окну, или даже к новому консольному окну, если это необходимо). После подключения к консоли окна консоли.WriteLine () etc работает так, как ожидалось. Один из них заключается в том, что программа немедленно возвращает управление в окно консоли, а затем продолжает писать в него, поэтому пользователь может также введите в окне консоли. Вы можете использовать start с параметром /wait, чтобы справиться с этим, я думаю.
перенаправление вывода консоли Это когда кто-то передает вывод из вашей программы куда-то еще, например.
прикрепление к окну консоли в этом случае эффективно игнорирует трубопроводы. Чтобы сделать эту работу вы можете вызвать консоль.OpenStandardOutput() для получения дескриптора поток, в который должен передаваться вывод. Это работает только в том случае, если вывод передается по конвейеру, поэтому, если вы хотите обработать оба сценария, вам нужно открыть стандартный вывод и записать его и прикрепить к окну консоли. Это означает, что вывод отправляется в окно консоли и в трубу, но это лучшее решение, которое я мог найти. Ниже код, который я использую для этого.
Как в C# Windows Form вывести консоль внутри исполняемой программы?
В Visual C# есть консоль или по другому вывод. В ней делается вывод работы программы, запуск и тд.
Хочу вывести эту самую консоль в самой программе. Чобы после компиляции нажать на какуюто кнопку и открылось окно консоли в котором будет выводится вся работа программы.
И соответственно в течение работы выводить в ней с помощью Console.WriteLine();
- Вопрос задан более трёх лет назад
- 5604 просмотра
Rou1997: Ладно. Я изменил на консольное приложение. А можно как-то сделать фичю чтобы её можно было скрыть. А то не всегда удобно. Да и вообще по возможности я хотел встроить её в саму программу. Чтобы она внизу в качестве выдвижной панели была. Хотя это не особо важно. Главное сейчас сделать чтобы её скрыть.
Ну ладно. В принципе можно и создать класс отвечающюю за консоль и создать свою консоль.
Может ответите на вопрос выше, так для моего развития. Я вижу вы знающий чел =)
how to run a winform from console application?
How do I create, execute and control a winform from within a console application?
10 Answers 10
The easiest option is to start a windows forms project, then change the output-type to Console Application. Alternatively, just add a reference to System.Windows.Forms.dll, and start coding:
The important bit is the [STAThread] on your Main() method, required for full COM support.
Exe netcoreapp3.1 true true
notice the Microsoft.NET.Sdk.WindowsDesktop and the UseWPF>true and the UseWindowsForms>true – Shaybc Aug 4 ’20 at 2:38
I recently wanted to do this and found that I was not happy with any of the answers here.
If you follow Marc’s advice and set the output-type to Console Application there are two problems:
1) If you launch the application from Explorer, you get an annoying console window behind your Form which doesn’t go away until your program exits. We can mitigate this problem by calling FreeConsole prior to showing the GUI (Application.Run). The annoyance here is that the console window still appears. It immediately goes away, but is there for a moment none-the-less.
2) If you launch it from a console, and display a GUI, the console is blocked until the GUI exits. This is because the console (cmd.exe) thinks it should launch Console apps synchronously and Windows apps asynchronously (the unix equivalent of «myprocess &»).
If you leave the output-type as Windows Application, but correctly call AttachConsole, you don’t get a second console window when invoked from a console and you don’t get the unnecessary console when invoked from Explorer. The correct way to call AttachConsole is to pass -1 to it. This causes our process to attach to the console of our parent process (the console window that launched us).
However, this has two different problems:
1) Because the console launches Windows apps in the background, it immediately displays the prompt and allows further input. On the one hand this is good news, the console is not blocked on your GUI app, but in the case where you want to dump output to the console and never show the GUI, your program’s output comes after the prompt and no new prompt is displayed when you’re done. This looks a bit confusing, not to mention that your «console app» is running in the background and the user is free to execute other commands while it’s running.
2) Stream redirection gets messed up as well, e.g. «myapp some parameters > somefile» fails to redirect. The stream redirection problem requires a significant amount of p/Invoke to fixup the standard handles, but it is solvable.
After many hours of hunting and experimenting, I’ve come to the conclusion that there is no way to do this perfectly. You simply cannot get all the benefits of both console and window without any side effects. It’s a matter of picking which side effects are least annoying for your application’s purposes.