在本地 Linux 计算机开发设置中监视和诊断服务Monitor and diagnose services in a local Linux machine development setup

监视、检测、诊断和故障排除允许服务继续运行,同时对用户体验造成最小中断。Monitoring, detecting, diagnosing, and troubleshooting allow for services to continue with minimal disruption to the user experience. 在实际部署的生产环境中,监视和诊断至关重要。Monitoring and diagnostics are critical in an actual deployed production environment. 如果在开发服务期间采用类似的模型,则转移到生产环境后,可以确保诊断管道能够正常工作。Adopting a similar model during development of services ensures that the diagnostic pipeline works when you move to a production environment. Service Fabric 使服务开发人员能够轻松实现可以跨单个计算机本地开发安装和实际生产群集安装无缝工作的诊断。Service Fabric makes it easy for service developers to implement diagnostics that can seamlessly work across both single-machine local development setups and real-world production cluster setups.

调试 Service Fabric Java 应用程序Debugging Service Fabric Java applications

对于 Java 应用程序,可以使用 多个日志记录框架For Java applications, multiple logging frameworks are available. 由于 java.util.logging 是 JRE 的默认选项,因此也适用于 GitHub 中的代码示例Since java.util.logging is the default option with the JRE, it is also used for the code examples in GitHub. 以下内容说明如何配置 java.util.logging 框架。The following discussion explains how to configure the java.util.logging framework.

使用 java.util.logging 可将应用程序日志重定向到内存、输出流、控制台文件或套接字。Using java.util.logging you can redirect your application logs to memory, output streams, console files, or sockets. 对于其中的每个选项,框架中已提供默认处理程序。For each of these options, there are default handlers already provided in the framework. 可以创建 app.properties 文件来配置应用程序的文件处理程序,将所有日志重定向到本地文件。You can create a app.properties file to configure the file handler for your application to redirect all logs to a local file.

以下代码片段包含一个示例配置:The following code snippet contains an example configuration:

handlers = java.util.logging.FileHandler

java.util.logging.FileHandler.level = ALL
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.FileHandler.limit = 1024000
java.util.logging.FileHandler.count = 10
java.util.logging.FileHandler.pattern = /tmp/servicefabric/logs/mysfapp%u.%g.log

app.properties 文件指向的文件夹必须存在。The folder pointed to by the app.properties file must exist. 创建 app.properties 文件后,还需要修改 <applicationfolder>/<servicePkg>/Code/ 文件夹中的入口点脚本 entrypoint.sh,将属性 java.util.logging.config.file 设置为 app.properties 文件。After the app.properties file is created, you need to also modify your entry point script, entrypoint.sh in the <applicationfolder>/<servicePkg>/Code/ folder to set the property java.util.logging.config.file to app.properties file. 该入口点应如以下代码片段中所示:The entry should look like the following snippet:

java -Djava.library.path=$LD_LIBRARY_PATH -Djava.util.logging.config.file=<path to app.properties> -jar <service name>.jar

此设置会导致在 /tmp/servicefabric/logs/ 中以轮替方式收集日志。This configuration results in logs being collected in a rotating fashion at /tmp/servicefabric/logs/. 本示例中的日志文件名为 mysfapp%u.%g.log,其中:The log file in this case is named mysfapp%u.%g.log where:

  • %u 是唯一编号,用于解决同时进行的 Java 进程之间的冲突。%u is a unique number to resolve conflicts between simultaneous Java processes.
  • %g 是生成编号,用于区分轮换日志。%g is the generation number to distinguish between rotating logs.

默认情况下,如果未显式配置处理程序,会注册控制台处理程序。By default if no handler is explicitly configured, the console handler is registered. 可以在 /var/log/syslog 下查看 syslog 中的日志。One can view the logs in syslog under /var/log/syslog.

有关详细信息,请参阅 GitHub 中的代码示例For more information, see the code examples in GitHub.

调试 Service Fabric C# 应用程序Debugging Service Fabric C# applications

可以使用多个框架在 Linux 上跟踪 CoreCLR 应用程序。Multiple frameworks are available for tracing CoreCLR applications on Linux. 有关详细信息,请参阅用于记录的 .NET 扩展.。For more information, see .NET Extensions for Logging. 由于 C# 开发者熟悉 EventSource,因此本文使用 EventSource 在 Linux 上跟踪 CoreCLR 示例。Since EventSource is familiar to C# developers,`this article uses EventSource for tracing in CoreCLR samples on Linux.

第一步是添加 System.Diagnostics.Tracing,以便可以将日志写入内存、输出流或控制台文件。The first step is to include System.Diagnostics.Tracing so that you can write your logs to memory, output streams, or console files. 要使用 EventSource 进行日志记录,请将以下项目添加到 project.json:For logging using EventSource, add the following project to your project.json:

"System.Diagnostics.StackTrace": "4.0.1"

可以使用自定义 EventListener 侦听服务事件,并将它们相应地重定向到跟踪文件。You can use a custom EventListener to listen for the service event and then appropriately redirect them to trace files. 下面的代码片段展示使用 EventSource 和自定义 EventListener 进行日志记录的实现示例:The following code snippet shows a sample implementation of logging using EventSource and a custom EventListener:


public class ServiceEventSource : EventSource
{
        public static ServiceEventSource Current = new ServiceEventSource();

        [NonEvent]
        public void Message(string message, params object[] args)
        {
            if (this.IsEnabled())
            {
                var finalMessage = string.Format(message, args);
                this.Message(finalMessage);
            }
        }

        // TBD: Need to add method for sample event.

}

internal class ServiceEventListener : EventListener
{

        protected override void OnEventSourceCreated(EventSource eventSource)
        {
            EnableEvents(eventSource, EventLevel.LogAlways, EventKeywords.All);
        }
        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
                using (StreamWriter Out = new StreamWriter( new FileStream("/tmp/MyServiceLog.txt", FileMode.Append)))
                {
                        // report all event information
                        Out.Write(" {0} ", Write(eventData.Task.ToString(), eventData.EventName, eventData.EventId.ToString(), eventData.Level,""));
                        if (eventData.Message != null)
                                Out.WriteLine(eventData.Message, eventData.Payload.ToArray());
                        else
                        {
                                string[] sargs = eventData.Payload != null ? eventData.Payload.Select(o => o.ToString()).ToArray() : null; 
                                Out.WriteLine("({0}).", sargs != null ? string.Join(", ", sargs) : "");
                        }
                }
        }
}

上述片段将日志输出到 /tmp/MyServiceLog.txt 中的文件。The preceding snippet outputs the logs to a file in /tmp/MyServiceLog.txt. 此文件名需要相应地更新。This file name needs to be appropriately updated. 如果要将日志重定向到控制台,请在自定义的 EventListener 类中使用以下片段:In case you want to redirect the logs to console, use the following snippet in your customized EventListener class:

public static TextWriter Out = Console.Out;

C# 示例中的示例使用 EventSource 和自定义 EventListener 在文件中记录事件。The samples at C# Samples use EventSource and a custom EventListener to log events to a file.

后续步骤Next steps

添加到应用程序中的跟踪代码也可用于诊断 Azure 群集中的应用程序。The same tracing code added to your application also works with the diagnostics of your application on an Azure cluster. 请查看以下文章,其中介绍了不同的工具选项,以及如何设置这些选项。Check out these articles that discuss the different options for the tools and describe how to set them up.