1. Wae logeun contexyteuga pilyohal까
Apeullikeisyeoni jakgeumyeon contexyteuga eops-eodo doendago 느끼기 쉽습니다: “add jeone parsega iss-eoss-eo”라고 우리 스스로 기억하고 있으니까요. Hajiman keomandeuga yeoreogae, cheori dan-gyega yeoreogae, helpeo hamsooga myeot gae, geurigo hana라도 olyuga saenggigi sijakhaneun sun-gan, logneun “dareun chaeteu-e daeap-haneun saramdeul” cheoreom boigi sijakhapnida. Munjayeol-eun boneunde, geu jung eotteon geotdeuli han gagat eun yeongnyeog-ui han beonjjae jageob-e soksokhan geos-indeunji al su eopsseubnida.
Yesireul 들어, uri 콘솔 지출 트래커(편의상 ExpenseTracker라고 부르겠습니다)가 add 120 food 커맨드를 처리한다고 합시다. Cheori gwajeong-eseo myeot 가지 haengdong-eul hamnida: munjayeol-eul 읽고, parse하고, validate하고, gilog-eul 추가하고, gyeolgwaeul 출력합니다. Loge “Started”, “Parsed”, “Saved” jeongdo ppunirago 하면, 빠르게 두 커맨드가 연속으로 들어올 때 logga seok-ineun 상황을 eopsji geotcheoreom boige doeeo “'Saved'ga cheot beonjjae 커맨드 geoya? du beonjjae geoya?”라고 추측하게 됩니다.
Yeogineun “contexyteu eopsneun log”ui jeonhyeongjeogin yesiibnida (kodeuga anira, konsol-eseo boreuneun geot):
1700000000000 [INFO] Command received
1700000000100 [INFO] Parsed command
1700000000150 [INFO] Command received
1700000000200 [INFO] Saved expense
1700000000250 [INFO] Parsed command
1700000000300 [INFO] Saved expense
Nuneun iksukhan dan-eoreul boneunde, meorineun honran-eul 느낍니다. Yeongyeoldoen meseojideureul 같은 pilyeodeul-ui 집합으로 “kkeup”hae jul su inneun bangbeob-i pilyohapnida.
2. Log contexyteu: mueosigo wae pilyohalkka
Log contexyteuneun meseoji-reul ddeo-batdeun “jak-eun key-value pilyeod”ui mog-eum-uro, “eotteon teureul an-eseo ireon il-ini?”reul daedaphamnida. 즉 meseojineun “mueos-i il-eonasseuni”reul malhago, contexyteuneun “mueotgwa yeongwan doe-eossneuni”reul jeongmilhage haejubnida: eotteon 커맨드인지, eotteon requestId인지, eotteon sayongja ibryeog인지, eotteon silhaeng modeu인지.
Jung-yohan jeom: contexyteuneun modeun geoseul messagee ugeujyeo neohneun 시도ga 아닙니다. Bandae-ro, messagereul 짧고 saramchireoun munjang-euro 유지하고(Expense saved), detail-eun gujo-euro bbaenida (amount=120 category=food requestId=req-42). Geureomyeon logneun nuneuro chajgi swipgo, filterhagi-do swip습니다 (jigeumun “nuneuro” + Ctrl+F ppun-ira-do).
Ireon sig-euro saeng-gakhal su itsseubnida:
| Logui bubu | Mueose daehae dap-haneunga | Yesi |
|---|---|---|
|
“mueos-i il-eonasseo?” | |
|
“mueot-e gwanlyeondoeeo?” | |
Ije logga “jeongsangjeogin 엔지니어링 heunjeok”cheoreom boigi sijakhapnida. peurogeuraem-ui gamjeong ilgi-ga 아닙니다.
3. Contexyteureul Map<String, String>ro
Contexyteuga dan-sunhago, yeongyeonhage, geurigo iksukhage doerok 하기 위해, Map<String, String>ro jeojanghagetseubnida. Igeun munje-e 딱 맞습니다: Mapeun key-value 쌍을 jeojanghago, keyneun yuil합니다 (hana-ui keyeun hana-ui value). Kotlineseo mappingeun yeoreoe gae-ui entries(key-value 쌍)ro guseongdoe며, keyreul munjayeol로 두면 편리한 gyeongu-ga manh습니다.
Gajang gan-danhan geosbuteo sijakhae bopsida: mapOf(...)ro contexyteureul jikjeob mandeulseubnida:
fun main() {
val ctx = mapOf(
"requestId" to "req-42",
"command" to "add"
)
println(ctx["requestId"]) // req-42
}
Yeogiui keyneun “yak-sok”ibnida. Kotlin-eun han gose "reqId"reul sseugo dareun gose "request_id"reul sseuneungeol magji anhjiman, geureomyeon gyeolguk gosaenghaneun geon jasin입니다. Geuraeseo cheoeum buteo keyreul “mini-API”cheoreom daeruhago, 안정적으로 유지haeya 합니다.
Tto hana jung-yohan jeom: value 타입으로 Stringreul seontaeghan i-yuneun “yuteu”라서ga 아니라, logga gyeolguk 텍스트로 출력되기 때문입니다. Eochapi modeun gapseul munjayeollo bakkwo야 합니다. Map<String, Any?>ro 하면 jayudo-neun keojiman, choboja-ga “gaekche jeonche”reul geudaero loghago sip-eojeo kilomeoteo gireui munjayeol-eul mandeulgi 쉽습니다. Uri-neun anjeonhan “sandbox”e namseubnida: munjayeolman.
4. Contexyteureul munjayeollo formatting
Jageum, contexyteuneun 있습니다. Hajiman println(ctx)neun {requestId=req-42, command=add}gateun geoseul 출력합니다 — eotteon ttaeneun 괜찮지만, uri-neun logga hang상 같은 mo양-euro boidolog 하는 dan-il hyeongsigi pilyohapnida. 그래야 chajgi swipgo, nuneuro noldae-bogi swip습니다. Gajang ilbanjeogin “saram chin-hwa” hyeongsig-eun 공백으로 gubun-doen key=value입니다.
Munjayeol-eul jochap-haneun 데는 joinToString()ga 아주 좋습니다: elementdeul-eul jeonghaejin 규칙(gu bunja, prefix 등)에 따라 하나-ui munjayeollo mandeul어 줍니다.
formatCtx(...) hamsooreul sseubnida. Contexyteuga bilmyeon 빈 munjayeol-eul 반환해야 합니다(geuraeya bulyo-han 공백-eul 출력하지 않습니다). Pilyeodga isseumyeon 앞에 공백을 하나 붙입니다:
fun formatCtx(ctx: Map<String, String>): String {
if (ctx.isEmpty()) return ""
return ctx.entries.joinToString(
prefix = " ",
separator = " "
) { (k, v) -> "$k=$v" }
}
Yeogie jag-eun “magi”ga 있습니다. ctx.entriesneun Map.Entryui 집합이고, dekonstruksyeon (k, v)reul sseose it.keywa it.valuereul an sseo-do 되게 합니다.
Gyeolgwareul hwag-inhae bopsida:
fun main() {
val ctx = mapOf("requestId" to "req-42", "command" to "add")
println("Hello" + formatCtx(ctx))
// Hello requestId=req-42 command=add
}
Ije logga “seongin-ui gye-eob”cheoreom boige doel geos입니다. printlnman jinjja joh-ahaneun saramcheoreom boiji 않게 되죠.
Pilyeod-ui sunseo
Contexyteuga jak-eumyeon sunseoneun geuri jung-yohaji 않습니다. Hajiman 같은 contexyteuga hang상 같은 hyeongsig-euro 출력되길 원한다면(줄-eul nuneuro bigyo-hagi swipseubnida), keyreul 정렬할 수 있습니다.
Deo “kkal-kkeumhan” beojeon-euro, hajiman yeojeonhi dan-sunhage 갑니다:
fun formatCtxSorted(ctx: Map<String, String>): String {
if (ctx.isEmpty()) return ""
return ctx.entries
.sortedBy { it.key }
.joinToString(prefix = " ", separator = " ") { (k, v) -> "$k=$v" }
}
Ne, jeongryeol-eun chuga jag-eob-iji man, gyoyuk-yong konsol aepjeongdo-eseoneun gwaenchanhgo, ilgeumseong-i deo joh-ajipnida.
5. Logger eobdeiteu: APIe contexyteu chuga
Hyeonjae loggeoneun timestamp, level, messageleul 출력할 수 있습니다. Uri-ui mokpyo-neun message 뒤에 se beonjjae 조각으로 formatCtx(ctx)reul 붙이는 것입니다. Jung-yohan geon, 호출하는 kodeuga formattinge daehae saeng-gakhaji 않게 하고, data만 넘기도록 만드는 것입니다.
Araeneun uri-ga ije-kkaji mandeun geosgwa 호환되는 Loggerui choesohan beojeon입니다: minLevel, ordinale uihan check, dan-il hyeongsig:
class Logger(private val minLevel: LogLevel) {
private fun enabled(level: LogLevel): Boolean =
level.ordinal >= minLevel.ordinal
fun log(level: LogLevel, message: String, ctx: Map<String, String> = emptyMap()) {
if (!enabled(level)) return
val ts = System.currentTimeMillis()
println("$ts [$level] $message" + formatCtx(ctx))
}
fun info(message: String, ctx: Map<String, String> = emptyMap()) =
log(LogLevel.INFO, message, ctx)
}
Gibon parameteoreul bwaseyo: ctx: Map<String, String> = emptyMap(). Ireomyeon yejeon cheoreom logger.info("Started")gateun 호출-eun 깨지지 않고, saeroun kodeuneun logger.info("Started", ctx)cheoreom contexyteureul chuga할 수 있습니다.
6. Hana-ui yogeong — hana-ui contexyteu
Contexyteuneun “geuttae geuttae tteo-olreum ttae” buteo 붙이는 게 아니라, ireoke saeng-gakhal ttae jin짜 유용해집니다: modeun operasiyeon-eun gibon contexyteureul gajinda, geurigo geugeol yeoreoe loge seojaehae boksu-ro jaesayong한다.
Konsol aep-eseo operasiyeon-eun ye: hana-ui 커맨드 cheori입니다. Geureomyeon requestId(korelleisyeon 식별자)가 pilyohapnida. Igeun 암호학적으로 강할 pilyo도 없고, jeonsegyejeog 융tabhan yuilseong도 pilyo 없습니다. “aep silhaeng han beon an-eseo dareumyeon doenda” jeongdo면 충분합니다.
Gajang gan-danhan saengseonggi:
fun newRequestId(): String {
val ts = System.currentTimeMillis()
return "req-$ts"
}
Ne, dangsin-i eomcheong ppalli silhaenghaneun 로봇이라서 같은 milliseconde-eseo du 커맨드를 boonaemyeon 충돌이 날 수도 있습니다. Hajiman gyoyuk peurojekteu sujun-eseoneun pyeonhi 살 수 있습니다.
Ije 커맨드ui gibon contexyteu:
fun commandCtx(requestId: String, rawLine: String): Map<String, String> {
return mapOf(
"requestId" to requestId,
"raw" to rawLine
)
}
Gajang joheun jeom: + 연산자로 contexyteue pilyeodeul-eul “chuga”할 수 있습니다. Map + Pairneun saeroun map-eul 반환하고 (gijon map-eul mutate 하지 않습니다):
fun main() {
val base = mapOf("requestId" to "req-42")
val extended = base + ("command" to "add")
println(extended)
// {requestId=req-42, command=add}
}
Ireoke 하면 kkalkkeumhan 스타일이 됩니다: gibon contexyteuneun operasiyeon gakkai-e isseogo, detail-eun pilyohan gose-eseo man chuga합니다.
7. null eopsneun contexyteureul wihan helpeo ctxOf(...)
Deo maneun detail-eul loghagi sijakhahmyeon bulpyeonhan jeom-eul balgyeon합니다: eotteon gapseun “jamkkan al su eopsneun” gyeongu-ga 있다는 것입니다. Ye: categoryga ajik parse되지 않았거나, amountga 잘못되어 있거나 등. Contexyteue "category" to "null"gateun geoseul neohgo sipji 않습니다 — jabeum만 keojipnida.
Geuraeseo jag-eun yutil ctxOf(...)reul mandeureumyeon 유용합니다. I hamsooneun key to value 쌍을 받아 value를 munjayeollo bakkugo, nulleun kkalkkeumhage beor립니다. Yeogiseo mapNotNulli jal 맞습니다. geugeon “byeonhwanhadeunji, beoriraji”reul jal 표현하거든요.
Gan-danhan beojeon:
fun ctxOf(vararg pairs: Pair<String, Any?>): Map<String, String> {
return pairs
.mapNotNull { (k, v) -> v?.toString()?.let { k to it } }
.toMap()
}
Sayong:
fun main() {
val amount: Int? = null
val ctx = ctxOf(
"requestId" to "req-42",
"amount" to amount, // null — will be omitted
"command" to "add"
)
println(ctx) // {requestId=req-42, command=add}
}
I hamsooneun contexyteureul kompakteu하게 만듭니다: “bi-eo itneun jeongbo”reul 출력하지 않습니다. Geurigo ne, i geos-eun jag-eun “ttokttokhan” helpeoga jinjja로 ilgeumseong-eul nop-ineun 드문 경우입니다. saenghwareul boks잡하게 하기보단 오히려 단순하게 합니다.
8. Silje yesi: ExpenseTrackereseo 커맨드 cheori
Ije modeun geoseul hana-ui seutori-ro mueoreobopseubnida. Uri-egeun munjayeol 커맨드를 읽고 처리하는 konsol aep-i 있습니다. Jigeumeun addwa list 커맨드만 지원하고, nareun geoseun olyu로 chibuh겠습니다. Sayongja에게 bo이는 출력(즉, 사람이 보는 것)은 평범한 println("...")로 두고, logneun loggerreul 통해 남깁니다.
Cheoeumeun 커맨드를 Pair로 parse합니다: 커맨드와 나머지 문자열. (Ne, deo areumdapge 할 수도 있지만, uri-neun log contexyteue 초점을 두고 있습니다.)
fun splitCommand(line: String): Pair<String, String> {
val trimmed = line.trim()
val firstSpace = trimmed.indexOf(' ')
if (firstSpace == -1) return trimmed to ""
return trimmed.substring(0, firstSpace) to trimmed.substring(firstSpace + 1)
}
Ije hana-ui 줄을 처리하는 핸들러. Jugmok할 점: requestIdreul 딱 한 번 만들고, 여러 log에서 재사용합니다.
fun handleLine(line: String, logger: Logger) {
val requestId = newRequestId()
val baseCtx = ctxOf("requestId" to requestId, "raw" to line)
logger.info("Command received", baseCtx)
val (cmd, rest) = splitCommand(line)
val cmdCtx = baseCtx + ("command" to cmd)
logger.info("Command parsed", cmdCtx)
// User output is separate from logs
println("OK, I got command: $cmd") // OK, I got command: add
}
Yeoreobeon 연속 실행하면, 각 “chain”ui logreul requestIdro muk-eul su 있음을 볼 수 있습니다:
1700000000000 [INFO] Command received requestId=req-1700000000000 raw=add 120 food
1700000000001 [INFO] Command parsed requestId=req-1700000000000 raw=add 120 food command=add
OK, I got command: add
Sigan-e 따라 logga seok-ide라도, requestIdga “seon”cheoreom 이벤트를 yeongyeolhae ju는 do구가 됩니다.
Cheori heureum-e 대한 jag-eun doro
“Contexyteuneun han beon mandeulgo operasiyeon jeon cheoreul tonghae gaji-go ganeunda”는 gaenyeom-eul 고정하려면, 커맨드 처리를 jjalb-eun 컨베이어로 saeng-gakhae 보는 게 도움이 됩니다:
flowchart TD
A["readln()"] --> B[requestId + baseCtx]
B --> C[log: Command received]
C --> D[parse command]
D --> E[log: Command parsed + command]
E --> F[execute]
F --> G[log: Command finished]
Contexyteuneun bbyeol-ui dan-gyega 아니라, dan-gyeodeureul ttakttak butyeo ju는 “kkeul”입니다.
Hyeongsig: jjalb-eun meseoji + detail-eun contexyteue
Boseyo, meseojineun gajang gan-dan합니다: Command received, Command parsed. Meseoji 텍스트에 “seosi”reul sseuji 않습니다. seosineun nuneuro chajgi himde니까요. Bandae-ro contexyteuneun jeongmilseong-eul ju죠: raw=... command=... requestId=....
Contexyteue mueoseul neohalkka
Contexyteuneun swipge “s레기통”i 될 수 있습니다: “ge냥 da neohja”. Geureomyeon 한 줄이 화면 한 페이지 길이가 되고, yuyongseong-eun 0이 됩니다. Geuraeseo 세 가지 규칙을 saeng-gakhae duseyo: contexyteuneun 이벤트를 yeongyeolhaeya 하고, munje 진단에 도움이 되어야 하며, neohneun naeyong-i 안전해야 합니다.
Uri CLI aep-eseoneun daedaero ijeongdo pilyeodeumyeon 충분합니다:
| Key | Uimi | Yesi |
|---|---|---|
|
hana-ui operasiyeon-e 속한 meseojideul yeongyeol | |
|
eotteon 커맨드를 silhaeng jung인지 | |
|
wonbon 커맨드 munjayeol | |
|
geumaek(isseul ttae) | |
|
kategori(isseul ttae) | |
Jugmok: uri-neun “aepui jeonche sangtae”나 “modeun 지출”eul loghaji 않습니다. “modeun geoseul loghago sipda”raneun saeng-gak-i 든다면, daedaero “eotteon data-ga jinjja jung-yohanji ajik jeongri an doeeossda”neun 신호일 때가 많습니다.
Tto key 스타일도 합의해 두세요. Kotlin kode-eseoneun camelCase(requestId, userId, tookMs)ga 보기 좋습니다. request_idwa requestIdreul 섞기 시작하면, 일주일 뒤에는 “wae geomsaeg-i an doejyo”라고 쓰고 창밖을 우울하게 보게 될 겁니다.
9. Log contexyteu sayong si jaju 하는 silsu
Oryu 1: contexyteureul meseoji 텍스트에 직접 “bak-a 넣는다”.
logger.info("Command received requestId=$id raw=$line")cheoreom sseumyeon detail-eul chuga-han deuthajiman, haeksim-eul ileobeor립니다: dan-il hyeongsig. Han gose-neun raw=..., dareun gose-neun input=..., tto dareun gose-neun 공백-eul 빼먹고, tto dareun gose-neun semikollon-eul jal못 넣는 식으로 “budam”i 커집니다. Contexyteuneun byeoldo-ui gujo(Map)ro 유지하고, formattingeun 엄격하게 Logger 안에서만 하세요.
Oryu 2: 같은 의미에 서로 다른 key를 쓴다.
Oneul-eun reqId, naeil-eun requestId, molegeun rid. Han 달만 지나도 logreul nuneuro bigyohal 수도 없고, dan순 검색조차 제대로 filtering이 안 됩니다. 한 번 key를 정하고(상수로 빼든, 합의로 하든) “미래의 나 자신을 위한 API”처럼 지키는 게 낫습니다.
Oryu 3: contexyteureul jogakjogak moa서 log마다 “tteodani게” 만든다.
Han meseoji-eseoneun requestIdga 있는데, da-eum meseoji-eseoneun 전달을 빼먹으면 — chain이 끊기고 korelleisyeonui idea-ga sarajim니다. Joh-eun 스타일은 operasiyeon cheoeum-e baseCtxreul 만들고, 그다음은 +로 확장해서 gibon pilyeodga jeoldae sageojiji 않게 하는 것입니다.
Oryu 4: contexyteue 너무 많은 값 또는 너무 큰 값을 넣는다.
Gisuljeog-euro-neun mae-u gin 텍스트나 serialize된 객체도 넣을 수 있지만, 나중에 읽는 건 지옥입니다. Contexyteuneun kompakteu해야 합니다: jjalb-eun 숫자, jjalb-eun ID, jjalb-eun status. “keun geos”eul loghago sip다면, daedaero geugeon byeoldo-ui 이벤트와 byeoldo-ui seolgye gae-im이지, contexyteu pilyeod hana로 해결할 문제가 아닙니다.
Oryu 5: contexyteureul mutable하게 만들고, log 시점의 값이 무엇인지 헷갈리게 “silsi-gan”으로 바꾼다.
MutableMapeul 쓰고 cheori jung pilyeodeul-eul chuga/jegeohamyeon, 모르게 같은 map-eul 여러 operasiyeon-eseo 재사용하게 되기 쉽습니다(특히 eodigae reference를 저장해 두면). Choboja에게는 immutable한 mapOf(...)와 +로 saeroun map-eul 만드는 방식이 더 안전하고 예측 가능합니다. Ne, geureomyeon saeroun objectga 생기지만, gyoyuk-yong konsol aep-eseoneun geu 비용이 작고, 예측 가능성의 가치는 큽니다.
Oryu 6: 출력하면 안 되는 데이터가 contexyteue 들어간다.
Gyoyuk peurojekteu-eseodo “logga eodideun nam-eul su 있다”neun 습관을 기르-myeon 좋습니다: terminal history, CI, file, 또는 누군가에게 보낸 log file. Geuraeseo cheoeum buteo discipline을 가지세요: contexyteuneun 기술 진단용이지 “uri-ga 아는 모든 것”이 아닙니다. 값-eul 찍어도 되는지 망설여진다면, daedaero-neun 찍지 않는 게 맞습니다(또는 축약해서 출력하세요).
GO TO FULL VERSION