Boost SpringBoot Log Management: Step‑by‑Step Integration with Hera
This article explains why traditional SpringBoot logging falls short, introduces the Hera log platform’s three core benefits, outlines a layered integration architecture, and provides a detailed five‑step guide—including Maven dependencies, YAML configuration, custom field providers, log output, traceability, and console usage—plus performance, high‑availability, security tips and common pitfalls.
Why Use Hera? Traditional Log Pain Points
Legacy SpringBoot logging either writes to local files or aggregates to ELK, leading to three major issues: scattered logs that make troubleshooting slow, broken request chains that prevent end‑to‑end traceability, and high storage costs caused by either full‑volume storage or lossy sampling.
Architecture: Layered Model for SpringBoot Integration
Log Collection Layer : Hera Agent is embedded in the SpringBoot app for non‑intrusive log capture and supports custom fields such as trace ID, user ID, and business tags.
Platform Layer : Core Hera service parses fields, applies business routing rules, and forwards logs.
Storage Layer : Critical logs are stored in Elasticsearch for fast search; archived logs are stored in HDFS to reduce cost.
Analysis Layer : Provides full‑text search, trace linking, and aggregation statistics.
Interaction Layer : Web console or OpenAPI lets developers query logs efficiently.
Practical Integration: 5 Steps
Environment Preparation : Deploy Hera platform (recommended version 2.5+) and add Maven dependencies.
<!-- Hera log client dependency -->
<dependency>
<groupId>com.hera</groupId>
<artifactId>hera-log-spring-boot-starter</artifactId>
<version>2.5.3</version>
</dependency>
<!-- Optional trace dependency for full‑chain logging -->
<dependency>
<groupId>com.hera</groupId>
<artifactId>hera-trace-spring-boot-starter</artifactId>
<version>2.5.3</version>
</dependency>Core Configuration : Define Hera settings in application.yml, focusing on agent addresses, log level, custom fields, and trace options.
spring:
application: order-service # service tag for Hera
hera:
log:
agent-address: 192.168.1.101:8888,192.168.1.102:8888
level: INFO
custom-fields:
- key: businessType
value: ${spring.application.name}-order
- key: env
value: ${spring.profiles.active:dev}
- key: userId
value-provider: com.example.order.config.HeraUserIdProvider
trace:
enabled: true
sampling-rate: 1.0
trace-id-header: X-Hera-Trace-IdCustom Field Provider : Implement HeraCustomFieldProvider to supply dynamic values such as the current user ID.
@Component
public class HeraUserIdProvider implements HeraCustomFieldProvider {
@Override
public String getValue() {
// Retrieve user ID from ThreadLocal (implementation depends on your auth layer)
UserContext context = UserContextHolder.getCurrentContext();
return context != null ? context.getUserId() : "unknown";
}
}Log Output : No code changes are required for existing SLF4J/Logback statements. Example service class shows automatic enrichment of logs.
@Service
public class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
public Order createOrder(OrderCreateDTO dto) {
Order order = new Order();
order.setOrderNo(generateOrderNo());
order.setUserId(dto.getUserId());
order.setAmount(dto.getAmount());
log.info("创建订单成功,订单号:{},用户ID:{}", order.getOrderNo(), order.getUserId());
try {
orderMapper.insert(order);
} catch (Exception e) {
log.error("创建订单失败,订单号:{},原因:{}", order.getOrderNo(), e.getMessage(), e);
throw new BusinessException("订单创建失败");
}
return order;
}
}Traceability & Console Usage : Enable trace ID propagation to link logs across services. In the Hera console, three steps locate key logs:
Filter by service name and environment.
Search using business fields (e.g., userId=1001 or orderNo=2024052014300001).
Click the trace ID to view the full request chain and expand exception stacks.
Advanced Topics: Performance, High Availability, Security
Performance Optimization : Use asynchronous collection (default), raise async queue size ( hera.log.async-queue-size=1024), limit log level to WARN in production, and batch transmission ( hera.log.batch-size=100).
High Availability : Deploy multiple Hera Agent nodes, enable local cache ( /tmp/hera/log/cache) for fallback, and store core logs in ES (7‑day fast search) while archiving to HDFS (30‑day retention).
Security Controls : Mask sensitive fields (e.g.,
hera.log.mask-fields=phone:138****1234,idCard:310***********1234), enforce service‑environment permissions, and audit all log‑view/export actions.
Pitfalls and Solutions
Missing custom fields : Caused by an unregistered or null‑returning HeraCustomFieldProvider. Fix by adding @Component and ensuring a non‑null value.
Trace loss across services : Often due to missing X-Hera-Trace-Id header or inconsistent configuration. Ensure all services share the same trace-id-header and propagate the header at the gateway.
High collection overhead : Result of excessive DEBUG logs or a too‑small async queue. Reduce log level, increase queue size ( hera.log.async-queue-size=2048), and monitor agent thread CPU usage.
Conclusion
Integrating Hera with SpringBoot is not merely a UI upgrade; it builds the observability foundation for distributed systems. It cuts troubleshooting time from hours to minutes, reduces storage costs by about 60%, and turns opaque services into a white‑box environment for rapid performance and business issue detection.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
