You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ballerina中记录HTTP监听器的启动与停止日志?

为Ballerina HTTP监听器添加启动与停止日志

要给这段Ballerina代码里的HTTP监听器加上启动、停止日志,你可以用Ballerina自带的log模块,结合两种方式实现:

方式一:手动管控监听器生命周期

显式调用监听器的启动、停止方法,在前后插入日志:

import ballerina/http;
import ballerina/log;

listener http:Listener httpListener = new(8080);

service / on httpListener {
    resource function get greeting() returns string { 
        return "Hello, World!"; 
    }
}

public function main() returns error? {
    log:printInfo("HTTP监听器正在启动,监听端口: 8080");
    check httpListener.start();
    log:printInfo("HTTP监听器启动完成");

    // 等待终止信号,保持服务运行
    check waitForShutdownSignal();

    log:printInfo("HTTP监听器正在停止");
    check httpListener.stop();
    log:printInfo("HTTP监听器已停止");
}

方式二:用监听器生命周期回调

HTTP监听器支持配置onStart和onStop回调,直接在监听器初始化时绑定日志逻辑,更贴合框架生命周期:

import ballerina/http;
import ballerina/log;

listener http:Listener httpListener = new(8080,
    onStart = function() returns error? {
        log:printInfo("HTTP监听器已启动,监听端口: 8080");
    },
    onStop = function() returns error? {
        log:printInfo("HTTP监听器已停止");
    }
);

service / on httpListener {
    resource function get greeting() returns string { 
        return "Hello, World!"; 
    }
}

注意点

  • 两种方式都需要导入ballerina/log模块,除了printInfo,你还可以根据需求用printDebug(调试日志)、printError(错误日志)等。
  • 方式一适合需要自定义启动前/停止后额外逻辑的场景;方式二更简洁,直接绑定监听器的生命周期事件。
  • 运行代码后,启动时会输出启动日志,按下Ctrl+C终止服务时会输出停止日志。

内容的提问来源于stack exchange,提问作者Nadeeshan Dissanayake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 12:11:10