Log.isDebugEnabled()使用场景

本文讨论了在使用Debug级别日志时为何需要先进行Log.isDebugEnabled()的判断。文章解释了这样做的原因是避免在非Debug模式下构造复杂的日志信息所造成的资源浪费,并提供了具体的使用示例。

  

  由于代码中部分日志想只在Debug模式下才打印出来,如果是Info模式就会显得太多了。所以很自然的就想到直接LOG.debug(……)。但是看到了以前一个大牛的代码,发现打印debug的时候都加了一层判断,就是Log.isDebugEnabled(),看着很奇怪,既然已经是Debug模式,为什么还需要加这么一层判断呢??

  自己搜索了一下,原来这个问题别人也注意过,给出了这样的回答,就是当要打印的debug信息比较复杂,比如我的就是,要把整个List打印出来,这时候就适合加Log.isDebugEnabled()判断,原因如果不加,LOG还是会构造里面的串,如果比较复杂,构造了却不打印,很浪费。所以这个时候最好加一层判断。

  当然,如果里面就是一个简单的字符串,还是可以直接LOG.debug(……)而不需加判断的。

  最后,记住这种使用模式:

if (LOG.isDebugEnabled()) {
    LOG.debug("Input Object/List/Map:" + Object/List/Map);
}

  

转载于:https://www.cnblogs.com/luceion/p/5867988.html

我在自定义sharding分片算法,请基于这个算法构造完整测试用例: import com.google.common.collect.Lists; import com.google.common.collect.Range; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue; import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue; import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm; import org.apache.shardingsphere.sharding.spi.ShardingAlgorithm; import org.springframework.stereotype.Component; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Locale; import java.util.Properties; /** * 自定义分片策略 * * @since 2025-08-18 */ @Slf4j @NoArgsConstructor @Component public class SalesDateShardingAlgorithm implements StandardShardingAlgorithm<String>, ShardingAlgorithm { private Properties properties; private static final String SEPERATOR = "-"; private static final String NOTABLE = "_NOT_EXIST"; private static final String TABLE_SDF = "%s_%s%s"; @Override public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) { String loginTableName = preciseShardingValue.getLogicTableName(); String date = preciseShardingValue.getValue(); if (log.isDebugEnabled()) { log.info(", sharding {} ", date); } String[] items = date.split(SEPERATOR, -1); if (collection.contains(StringUtils.lowerCase(String.format(TABLE_SDF, loginTableName, items[0], items[1])))) { return String.format(TABLE_SDF, loginTableName, items[0], items[1]); } return loginTableName + NOTABLE; } @Override public Collection<String> doSharding(Collection<String> availableTables, RangeShardingValue<String> rangeShardingValue) { Collection<String> tableList = Lists.newLinkedList(); String logicTableName = rangeShardingValue.getLogicTableName().toLowerCase(Locale.ROOT); Range<String> dates = rangeShardingValue.getValueRange(); try { if (log.isDebugEnabled()) { log.info("tableName : {}, begin : {} end : {}", logicTableName, dates.lowerEndpoint(), dates.upperEndpoint()); } // 动态计算日期范围 Date start = DateUtils.parseDate(dates.lowerEndpoint(), "yyyy-MM-dd HH:mm:ss"); Date end = DateUtils.parseDate(dates.upperEndpoint(), "yyyy-MM-dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); cal.setTime(start); while (cal.getTime().compareTo(end) == 0 || cal.getTime().before(end)) { String month = cal.get(Calendar.YEAR) + String.format("%02d", cal.get(Calendar.MONTH) + 1); String table = String.format(TABLE_SDF, logicTableName, month.substring(0, 4), month.substring(4)); if (availableTables.contains(table)) { tableList.add(table); } else { tableList.add(logicTableName + NOTABLE); } cal.add(Calendar.MONTH, 1); } } catch (Exception e) { log.error("doSharding error", e); throw new BffException(e.getMessage()); } if (log.isDebugEnabled()) { log.info("res : {}", tableList); } return tableList; } @Override public Properties getProps() { return properties; } @Override public void init(Properties properties) { this.properties = properties; } public String getType() { return "SalesDateShardingAlgorithm"; } }
最新发布
09-02
public void addActivityScore(Long userId, ActivityScoreBo activityScore) { if (userId == null) { return; } // 1. 计算活跃度(正为加活跃,负为减活跃) String field; int score = 0; if (activityScore.getPath() != null) { field = "path_" + activityScore.getPath(); score = 1; } else if (activityScore.getArticleId() != null) { field = activityScore.getArticleId() + "_"; if (activityScore.getPraise() != null) { field += "praise"; score = BooleanUtils.isTrue(activityScore.getPraise()) ? 2 : -2; } else if (activityScore.getCollect() != null) { field += "collect"; score = BooleanUtils.isTrue(activityScore.getCollect()) ? 2 : -2; } else if (activityScore.getRate() != null) { // 评论回复 field += "rate"; score = BooleanUtils.isTrue(activityScore.getRate()) ? 3 : -3; } else if (BooleanUtils.isTrue(activityScore.getPublishArticle())) { // 发布文章 field += "publish"; score += 10; } } else if (activityScore.getFollowedUserId() != null) { field = activityScore.getFollowedUserId() + "_follow"; score = BooleanUtils.isTrue(activityScore.getFollow()) ? 2 : -2; } else { return; } final String todayRankKey = todayRankKey(); final String monthRankKey = monthRankKey(); // 2. 幂等,判断之前是否有更新过相关的活跃度信息 final String userActionKey = ACTIVITY_SCORE_KEY + userId + DateUtil.format(DateTimeFormatter.ofPattern("yyyyMMdd"), System.currentTimeMillis()); Integer ans = RedisClient.hGet(userActionKey, field, Integer.class); if (ans == null) { // 2.1 之前没有加分记录,执行具体的加分 if (score > 0) { // 记录加分记录 RedisClient.hSet(userActionKey, field, score); // 个人用户的操作记录,保存一个月的有效期,方便用户查询自己最近31天的活跃情况 RedisClient.expire(userActionKey, 31 * DateUtil.ONE_DAY_SECONDS); // 更新当天和当月的活跃度排行榜 Double newAns = RedisClient.zIncrBy(todayRankKey, String.valueOf(userId), score); RedisClient.zIncrBy(monthRankKey, String.valueOf(userId), score); if (log.isDebugEnabled()) { log.info("活跃度更新加分! key#field = {}#{}, add = {}, newScore = {}", todayRankKey, userId, score, newAns); } if (newAns <= score) { // 日活跃榜单,保存31天;月活跃榜单,保存1年 RedisClient.expire(todayRankKey, 31 * DateUtil.ONE_DAY_SECONDS); RedisClient.expire(monthRankKey, 12 * DateUtil.ONE_MONTH_SECONDS); } } } else if (ans > 0) { // 2.2 之前已经加过分,因此这次减分可以执行 if (score < 0) { Boolean oldHave = RedisClient.hDel(userActionKey, field); if (BooleanUtils.isTrue(oldHave)) { Double newAns = RedisClient.zIncrBy(todayRankKey, String.valueOf(userId), score); RedisClient.zIncrBy(monthRankKey, String.valueOf(userId), score); if (log.isDebugEnabled()) { log.info("活跃度更新减分! key#field = {}#{}, add = {}, newScore = {}", todayRankKey, userId, score, newAns); } } } } }
03-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值