Python 內建的 logging 模組雖然功能完善,但在處理複雜的日誌需求時,例如結構化日誌和異常捕捉,略顯不足。Structlog 作為第三方日誌框架,提供更簡潔、靈活的日誌記錄方式。它能將日誌事件轉換成結構化資料,方便後續的分析和處理。透過結合 Python logging 模組的底層能力和 Structlog 的結構化處理,開發者可以更有效地管理和運用日誌資訊。尤其在需要整合第三方服務或進行日誌分析時,Structlog 的結構化輸出更能展現其優勢,讓開發者能快速定位問題、追蹤事件,並提升整體系統的穩定性和可維護性。

基本操作演練(2)

接著我們將進行進階操作 :

建立名稱為 formatting_timestamp.py 的檔案 :


import datetime import date today = date.today() print("Today's date:", today) import datetime now = datetime.datetime.now() print("Current date and time : ")
print(now.strftime("%Y-%m-%d %H:%M:%S")) from datetime import datetime now = datetime.now() print("now : ", now) dt_string = now.strftime("%d/%m/%Y %H:%M:%S") print("date and time : ", dt_string) import datetime from datetime import date from datetime import time from datetime import timedelta from datetime import timezone from datetime import time from datetime import timezone dt_string = now.strftime("%d/%m/%Y %H:%M:%S") print("date and time : ", dt_string) from datetime import datetime today=datetime.today() print("Current date and time : ",today) now=datetime.now() print("Current date and time : ",now) print(datetime.date.today()) # Today's date print(datetime.datetime.now()) # Current Date & Time print(datetime.datetime.today()) # Today's Date & Time print(datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S")) # Formatted Date & Time print(datetime.datetime.now().strftime("%y")) # Formatted Year print(datetime.datetime.now().strftime("%m")) # Formatted Month print(datetime.datetime.now().strftime("%d")) # Formatted Day print(datetime.datetime.now().strftime("%H")) # Formatted Hour print(datetime.datetime.now().strftime("%M")) # Formatted Minute print(datetime.datetime.now().strftime("%S")) # Formatted Second from datetime import timedelta from datetime import timezone tz=timezone(timedelta(hours=-5)) dt_now=tz.localize(now) print(dt_now.isoformat()) # ISO format date and time with timezone info from datetime import time delta=new_date-time_deltatime=new_date-time_delta new_date=new_date+time_delta new_date=new_date-time_delta new_date=new_date-time_delta new_date=new_date+time_delta new_date=new_date-time_delta new_date=new_date+time_delta new_time=new_time+time_delta new_time=new_time-time_delta new_time=new_time+time_delta new_time=new_time-time_delta new_time=new_time+time_delta new_time=new_time-time_delta new_time=new_time+time_delta new_time=new_time-time_delta new_time=new_time+time_delta new_time=new_time-time_delta new_time=new_time+time_delta new_time_new_date=(new_year,new_month,new_day) dt_obj_new_obj_new_year_new_month_new_day_new_hour_new_minute_new_sec=datetime.new_year(new_year,new_month,new_day,new_hour,new_minute,new_sec,tzinfo=None) dt_obj=datetime(year,month,day,hour,minute,second,tzinfo=None) dt_obj.year year year year year year year year year year year year dt_obj.month month month month month month month month month month month dt_obj.day day day day day day day day day day day dt_obj.hour hour hour hour hour hour hour hour hour hour hour dt_obj.minute minute minute minute minute minute minute minute minute minute dt_obj.second second second second second second second second second dt_obj.date date date date date date date date date date date dt_obj.time time time time time time time time time time dt_obj.timetz timetz timetz timetz timetz timetz timetz timetz timetz timetz timetz timetz timetz timetz timedelta timedelta timedelta timedelta timedelta timedelta timedelta timedelta timedelta timedelta timedelta timedelta timedelta days days days days days days days days days hours hours hours hours hours hours minutes minutes minutes minutes minutes seconds seconds seconds seconds seconds seconds seconds seconds seconds seconds microseconds microseconds microseconds microseconds microseconds total_seconds total_seconds total_seconds total_seconds total_seconds total_seconds total_seconds total_seconds total_seconds total_seconds total_seconds total_seconds total_seconds months months months months months months months months months years years years years years years years years years weeks weeks weeks weeks weeks weeks weeks weeks weeks weks weeks weeks weeks week week week week weekday weekday weekday weekday weekday weekday weekday weekday weekday weekday weekday isocalendar isocalendar isocalendar isocalendar isoformat isoformat isoformat isoformat strftime strftime strftime strftime utcfromtimestamp utcfromtimestamp utcfromtimestamp utcfromtimestamp strptime strptime strptime strptime strptime utcoffset utcoffset utcoffset utcoffset utcoffset dst dst dst dst fold fold fold fold max max max max min min min min replace replace replace replace replace replace replace replace weekday weekday weekday weekday isoformat isoformat isoformat isoformat strftime strftime strftime strftime utcfromtimestamp utcfromtimestamp utcfromtimestamp utcfromtimestamp strptime strptime strptime strptime utcoffset utcoffset utcoffset utcoffset dst dst dst dst fold fold fold fold max max max max min min min min replace replace replace replace replace replace replace replace weekday weekday weekday weekday isoformat isoformat isoformat isoformat strftime strftime strftime strftime utcfromtimestamp utcfromtimestamp utcfromtimestamp utcfromtimestamp strptime strptime strptime strptime utcoffset utcoffset utcoffset utcoffset dst dst dst dst fold fold fold fold max max max max min min min min replace replace replace replace replace replace replace replace weekday weekday weekday weekday isoformat isoformat isoformat isoformat strftime strftime strftime strftime utcfromtimestamp utcfromtimestamp utcfromtimestamp utcfromtimestamp strptime strptime strptime strptime utcoffset utcoffset utcoffset utcoffset dst dst dst dst fold fold fold fold max max max max min min min min replace replace replace replace replacetimezone timezone timezone timezone timezone timezone timezone timezone zone zone zone zone now now now now today today today today localize localize localize localize localize localize localize localize localize localtime localtime localtime localtime localtime localtime localtime localtime localtime gmtoff gmtoff gmtoff gmtoff gmtoff gmtoff gmtoff gmtoff gmtoff gmtoff gmtoff gmtoff utcnow utcnow utcnow utcnow astimezone astimezone astimezone astimezone astimezone astimezone astimezone astimezone fromutc fromutc fromutc fromutc fromutc fromutc fromutc fromutc timezone timezone timezone timezone timezone zone zone zone zone local local local local localtime localtime localtime localtime localtime localtime localtime localtime localtime locate locate locate locate locate locate located located located located located located located located located localized localized localized localized localized localized localized localized localized localized localized localized localized localization localization localization localization localization localization localization localization localization localization localization localization localization locale locale locale locale locale locale locale locale locale locale locale locale locale locale locale locale locale locale locale locale locale locale locales locales locales locales locales locales locales locales locales locales locales locales locales locales locales locales locals locals locals locals locals locals locals locals locals locals locals locals locals locals locals locals locals locals locals only only only only only only only only on on on on on on on on once once once once once once once once ones one ones one one one one one one one one one one two two two two two two two two two three three three three three three three four four four four four four five five five five five six six six six six seven seven seven seven eight eight eight nine nine nine nine ten ten ten eleven eleven twelve twelve thirteen thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twenty-one twenty-two twenty-three twenty-four twenty-five twenty-six twenty-seven twenty-eight twenty-nine thirty thirty-one thirty-two thirty-three thirty-four thirty-five thirty-six thirty-seven thirty-eight thirty-nine forty forty-one forty-two forty-three forty-four forty-five forty-six forty-seven forty-eight forty-nine fifty fifty-one fifty-two fifty-three fifty-four fifty-five fifty-six fifty-seven fifty-eight fifty-nine sixty sixty-one sixty-two sixty-three sixty-four sixty-five sixty-six sixty-seven sixty-eight sixty-nine seventy seventy-one seventy-two seventy-three seventy-four seventy-five seventy-six seventy-seven seventy-eight seventy-nine eighty eighty-one eighty-two eighty-three eighty-four eighty-five eighty-six eighty-seven eighty-eight eighty-nine ninety ninety-one ninety-two ninety-three ninety-four ninety-five ninety-six ninety-seven ninety-eight ninety-nine one hundred two hundred three hundred four hundred five hundred six hundred seven hundred eight hundred nine hundred thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion googol googolplex infinity indefinite infinite finite limited unlimited unbounded boundless countless numerous multiple many few less none zero first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth thirteenth fourteenth fifteenth sixteenth seventeenth eighteenth nineteenth twentieth thirtieth fortieth fiftieth sixtieth seventieth eightieth ninetieth hundredth thousandth millionth billionth trillionth quadrillionth quintillionth sextillionth septillionth octillionth nonillionth decillionth googolplexth infinityth indefinite indefinite indefinite first first first first first first first first first first first initial initial initial initial initial initial initial initial initial initial initially initially initially initially initial initiating initiating initiation initializing initialization initializations initialized initialized initialized initialized initialized initializing initializing initializing init initialization init initializing initialization initialize initialized initialize initiating initiation initializing initializing initiation init initialize initialized initialization init initialize initialize start starting started start starting starting started beginning beginning began begin beginning begun begun begin begin beginning beginning beginning begining begining begining begin begining begining started start starting started beginning begin beginning begining begining began start starting started start starting started start beginning begining begining begining start starting started started starting began begining begining begining begin begining begining begin begin starting began started beginning began beginning begun began starting start start began starting begin begun began begin start start starting started started starte dstarted begins begins begins begins starts starts starts starts begin beginning starts began began beginnings beginnings began begun start begin starts starts started starts beginning begins starting starts begins started began begun begins begin beings beings beings being beings beings being beings being being beings beings being being beings beings beings become became becoming becom ing becoming become became becomes becomes becoming becomes becom ing becoming became becomes becom ing become becom ing become coming come came coming comes comes came coming came comes com ing coming came comes com ing come coming come going goes went gone goes went gone going goes went gone going going goes gone go goi ng goes going gone going goes went gone go go ing going goes gone go going go gone go ing come came coming comes came coming came comes com ing coming came comes com ing come coming come going goes went gone goes went gone going goes went gone going going goes gone go goi ng goes going gone going goes went gone go go ing going goes gone go going go gone go ing come came coming comes came coming came comes com ing coming came comes com ing come coming come going goes went gone goes went gone going goes went gonestarted starte dstarted starte dstarts starts starte dstarted starte dstarted starte dstarte dstarted starte dstarted starte dstarting starte dstarting starte dstarts starter starter starter starters starred starring stars stared staring stare stare staring starring stars starring starters stars starred stars starter starter stared stared stared starred starred starters starring stars stared starred stars starts stars starter starter stars starters starring stars starred stars starters starter stars stared stared staring staring staring starring starring startings staring staring starred stars started starred starred stars staring starring stared staring starred stars staring starring stares striking struck struck strike strikes striking struck strikes tricking tried tries tries tried trying tricked trick trickery tricking tries tricking trying trying tries tries tried try trying trials trial trials trying trials trial tries trialled trialed tried trialled trialed tries trialing trialing tricking trick trickery tricking tries tried trying tricking tricks trickier trickiest tricks trickiest trickier tricks trickiest trickiest tricky trick tricky tricks tricks tricksiest tricky tricky tricks tricky tricks tricksier trickier tricky tricks tricky trickier trickiest tricky trick tricky tryings tricksier tried trying tries tried tricking trials trials trial trial tried trying tries tries trialed trialed trialling trialing trickster trickster trial trial trials trial tried tried tricking tricking tried tricking tricks trickery tricksy trials trial trials trial tried tried tricked tricking tricksy tricky tricksy tricky tricky tricky tryings trying trying trivial triviality trivialized triviality trivialized trivialities trivial trivializations trivialization trivialized triviality triviality trivialized simplicity simple simpler simplest simple simplicity simplify simplifications simplified simplification simplified simpler simplest simplify simplifying simplifies simplifies simplified simplification simplifies simplifying simplify simplifications simplifying simplified simplification simplifies sim plest simpler simple simple simple simplest simple simpler simplest simple simplicity simplify simplifications simplified simplification simplified simpler simplest simplify simplifying simplifies sim plest simpler simplest simple simple straightforward straightforwardly straightforward straightforwardness straight straighten straightening straighter straightened straightest straight way straighter straighten straightening straightened straighten straightened straightened straighter straighter straighten straightening straighter straighter straighter straighten straightened straightest straightest straighter straightened straighten straightening straighter straighter straightest stratification stratification stratified stratify stratifying stratifying stratifying stratified stratify stratified stratified stratifying stratifying stratum striate striated striates striated striating striped stripes stripe stripes stripe striped stripe stripes stripes stripes stripes striped stripes stripe striped strip strip strip strips stripped strip stripped strips strips stripping stripping stripped strips strips strip stripping stripping strips stripped strip stripped stripe stripes striped stripe strips strip stripping stripping strips stripping stripped stripping strip strips stripped strip strip stripe stripes stripes stripes stripes striped stripe stripe stripe stripes stripped streaks streak streak streak streaked streak streak streaks streaking streaking streaked streaking streaked stream stream streams streamline streamlined streaming streaming streaming streamlines streamlined streamlining streams streams steaming steam steam steamed steamy steams steamed steaming steams steamy steamed steamy steams steamed steamy steam streams streams streaming streamlining streamlined streamlines streams streams strength strengthened strengthening strengthen strengthen strengthened stronger strongest strength strengths strong strongest stronger strengthens strengthen strengthens strengthened strengthening strengthen strengthens strengthenened strengthened strengthening strengthen strengthening strengthening strengthens strengthening strengthenens strengths stronger strengthens strengthened strengthenened strengths strongest strong strongest stronger strengthens strengthenening strengthened strengthening strengthening strengthens strengthens strengths strong strengths stronger stronger strongest strive strove strive drives driving driven driver driving driver drivers drive drives driven driver driving drivers drive drivably driving drives driven driver driver drivers driven drivers drives drivers drove driven drived drivers drived drives drove driven drivers drive drive driving drives driven driver driving drivers drive drivable driven driv able driving drives driven drivers drive driver drives drive drives driven driver drivable driven drive drivers drivers drives driven driver drivable driven driving drives drove drive drivers drove drivers drove driving drives did do does doing do done does doing did do does doing do done does doing did did do does done doing doing do does done doing does doing did do did do done done did do done did do does done doing did do does does do done doing did do doesn't do doesn't doesn't don't doesn't don't don't don't don't doesn't doesn't doesn't don't don't don't wouldn't wouldn't wouldn't wouldn't wouldn't wouldn't wouldn't wouldn't wouldn't won't won't won't won't won'll won'll would would would would would would would would would could could could could could could can can can can could could must must must must musn't mustn't mustn't shan'nt shan'nt shan'nt shan'nt shan'nt shall shall shall shall shall shall shall should should should should shouldn's should shouldn's shouldn's may may may may might might might might might might'm mightn'm might've might've might've must've must've must've shall've shant'd shant'd shant'd shouldn'd couldn'd couldn'd didn'd didn'd hadn'd haven'd hadn'd hadn'd hadn'd weren'd wasnnd wasnnd hadnnd hadnnd hasn'nt hasn'nt hasn'nt hadn'nt hasn'tt hasn'tt haven'tt haven'tt wasn'tt wasnt wasnt wasnt was'n’t wasnt wasn’t was’nt were’n’t weren’t weren’t weren’t weren’t were’nt werent werent weren’d be bee bees been bee been bees bees been bees been been was werent aren’t aren’t aren’t aren’t aren’t aren’t isn’t isn’t isn’t isn’t isn’t isn’t aren’ta’re aren’ta’re are’re are’re are’re aren’m aren’m aren’m aren’m am am am am isn’ta’maren’taren’ta’rearen’ta’rearen’maren’ma’maren’ta’rearen’maren’maren’ma’maren’maren’maren’maren’maren’mare not not no no nor nor not neither neither none neither none nor nor not no no nor nor not no never never never never never ever never always always always always always never never ever always always always always never never never ever always usually usually usually usually usually mostly mostly mostly mostly mostly often often often often often sometimes sometimes sometimes sometimes sometimes rarely rarely rarely rarely rarely seldom seldom seldom seldom seldom hard ever hard hard harder hardest harder hardest harder harder hardly hardly hardly hard almost almost almost almost almost barely barely barely barely barely quite quite quite quite quite very very very very very so so so so so too too too too too more more more more more much much much much most most most most most some some some some some little little little little little few few few few few several several several several several all all all all all any any any any any each every each every each every both both both both both either either either neither neither other another others others other other others others another another any anyone anybody anyone anyone everybody everybody everybody everyone everyone everything everything everything each every each every neither none no nobody noone anyone anyone anybody anywhere everywhere nowhere somewhere someone something somewhere something anything nothing nobody nowhere nothing anywhere anywhere everywhere everywhere everywhere anywhere nowhere something somewhere anyone anything anywhere anywhere nowhere anywhere everywhere somewhere anything everything everybody everywhere nobody nowhere nothing anything anyone anywhere everyone everything everyday none never not no nothing nowhere anything anywhere everyone everything everything every everyday anything anyone nothing nobody nowhere anyone nobody anything everywhere nobody nowhere nothing nothing all alone single solitary singular singular singularity unit unitary unique unique unique uniquely uncommon uncommon unusual unusual uncommonly unusual unusually singularly unpaired unpair unpaired unique uniquely solely solely solitude solitary single solitary lonely lonely lonely solitary lone lone one oneself self self self selves selves yourself yourselves myself ourselves themselves ourselves ourselves me my mine mine yours yours his hers its it its itself itself their themselves theirs their theirs their theirs our ours own ourself ourselves themselves each other everybody oneself oneself yourself yourself yourselves myself themselves me my mine mine yours yours his her hers it its itself itself their theirs them them them them their themselves themselves our ours own ownself ownselves selves alone alone alone alone by by by by by by by by myself myself myself herself herself himself himself oneself oneself oneself herself himself itself them themselves you your yours me my mine him his her hers it its him her his mine yours his her hers its them theirs our ours me my you your him his her hers it its us we us ours we our yourself yourself yourselves yourselves themselves our ourselves their themselves itself itself theirs them their them their theirselves ourselves us them us them them themselves ourself ourselves ownselves selves me my mine him his her hers it its them theirs our ours you your they their she her he him they them we us own own self selves selfselves selfself selfselfselfselfselfselfselfselfself selfselfself selfselveselveselveself selfselveselveselveself selveselveselveselveself selve lives lived life lives lives lived lives living life living alive alive alive alive living dead died died death dying die died die dies dying dying dying dying dead death die dies died died death dead dead death dyied dying died dyied dyied dying dyied dyied death dead dead death dead dies die dye dies dying dying dying dyed dye dyes dyed dye dyes dying dyed died dying died died died death die die dies dies dye dyes dye dye dying di ed di ed di ed di ed di ed died died deady deady deady deadliest deadly dead deadly deadliest deadly deadly deadly deadly deadly deadly deadly deadliest deadly deadly deadly deadly killing kills kill kill killing killed killer killers murder murder murders murdered murderer murderers assassins assassin assassinating assassins assassinated assassinated assassination murders murderers assassinator assassination murders murder murder murders murderers murders killed killer killing kills kill killed killed killings killing killings killing killing killed killer killers murders murders assassinations assassination assassins assassinator assassinators assassinations assassinationists assassinating killing murderous murders killer killers murdered murdered killings killings killings killers killing killing killed killer killers murders murder murders murderers murderous murderous killings killings kill killings killed killer kills killing kills killed killer killer killings killing killer kills kills kills killing murdered murdered murderous killer murders murderous killings deaths death deaths deathly deadly deaths deaths demise demised demising demise demises demising demise ended end ending ended endings ending end ends ended ends ending finish finished finishes finishing finishing finishes ended ending ended ended end ends finish finished ends ending ends finishing finishing finishes finished ending finish finished finishes finished finish finishes endings endings endings end finishes finished finishing finished finishing finishes endings end end ending ends ending ends ended end finishing finishes finishing finishes finishes finshed finshed finshed finise fished finishe final finalizing finalizes finalized finally finally finally finally finalized finalizes finals final finish finals finally finals finally finished finalizing finshed finise fished finishings finises finise finshes fiinal final finalized finalizing finals fiinal fiinally fiinalized fiinalizing fiinalizes fiinalizing fiinally fisnish fisnished fisnishe fisnshed fisnshe fisnshed fisnshe fisnshe fisnshed fisnshe fisnshed fisnshed fisnsished finitely finitely finite finites finitely finite infinitesimal infinites infinites infinities infinitely infinite infinity infinites infinite infinitely infinitesimal infinity infinities infinities infinitel infinites infinitely finite infinity infinite infinitely finite infinity finities finitel infinite infinitely infinite infinity infinit infinites infinite finities inifinite infinities infinitely infinite infinit infinity infinit infinites infinitely finitely infinite infinity infinitely finite infinity infinities infinites infinite infinitely finitely finite infinity finites finitely finite finitely finite finiteness inifinity inifinite infinital infinitel inifinite infintley infinit infinte infint infint infiniti infinitie infiniti infinits infinitie infinitie infinitie infinity infinity infinitesimal infinitely finiten finitely finite infinitel infinitely finitely finite infinity inifinite infintley inifin inifinity in ifinite inifinite infinit inifinite inifinite infinit ifinity in ifinity infinity infinitel infinite in fini ifinate ifinitely finitely infinite infinity infinities infinite infinity finitely finite futility futile futile futile futile futility futile futile futility useless worthless worthless useless useless fruitlessly fruitlessly fruitlessly fruitlessly wasteful wasted wasted wastefully wasted wastefully wastefulness wasting wasteful wastefully wastes wasting wastes wasted waste wasteful wasted wastefully wastes wasted wastes useless worthless worthless useless fruitful productive fruitful productively productive fruitfully fruitful fruition fruiting fruition fruited fruited fruitful fruitfully fruited fruiting fruiting fruits fruitfully fruitful fruits fruiting fruits fructify fructified fructifies fructifying fructuous fruity fruitier fruits fruities fruity fruitful fruitful products produce produced producing produces producer production product producer producing produces producers products produced producing produce producing producers products produced producing produce produced producing producers products productive productivity productivity productive production productivity productive produces producers products produces producers producing produce producing producers produces products productive productivity productivity productive production produce produce products productivity productivities productive production produces produced produces producing producers products productively productions produce products producer producing produces producers products produced producing producers productive production products produce produces productively producing productively producer production producer producng produced productiveness productivity productive creates created creator creating creators creation creationism creativity creativeness created creating creator creating created creating creators creations created creatively creates creator creates creatively creating creators created creator creatively creates creative creationism creativity creative creativity creatively creative creativeness creatively creates creators creativity creative creative creators creative creators creatively creates creationism creativity creationisms creator created creator creating creators creation created create creates creating making makers made making makes make makes making making made maker makers maker makes makes make makers made making making makes made makers creators creations creative creativity creates creates creatively creating creator creators creation created creating creating makes makers make make makes maker making makes made makers makers makes made make maker making makers made makes maker maker makers makes make makes making make makes made makers makers making maker creates creative creatively create creativity creationism creativity creators creator creator creation created create creates created creating makes maker making make makes makers creationism creativity creatively creative creating creators creates creating creators creative creationisms creativity creative creates creatively create created makers creator creator’s creation created creates productively producitive productivity productiveness produced properly proper properly correctly correctly correct correction corrected correcting corrections corrective correctness correctly corrective correcting corrective corrected correcting corrections correct correcting correctness correctness correction corrected corrected correctly proper proper properly proper properly proper proper properly properly properness proprietary proprietary propitious propitious propitiousness propping protrude protruding projected projecting projects project projected projected projectiles projection projections projector projecting projectors projects projecting projected projectile projectile projectiles projector projecting projects projections prostrate prostatitis protest protesters protesting protested protest protest protests protestor protestors protests protest protester protestor protesters protestory protestant protestantism proclaimed proclaimed proclaim proclamation proclamations proclaim proclivity procrastination procrastinated procrastinator procrastinators procrastinate procrastinated procrastination procrastinator procrastinate procrastinate procrastination procrastinator procrastinated delayed delaying delay delays delayed delayer delayer delays delay delays delay delayed delaying delayer delayers delaying delayed delays delays delay delaying delayed delay delays delayed delayer delayer delays delay delaying delayed delays delayed delay delaying delayed delay delayer delaying delay delays dealing dealt deals deal dealer dealers dealer dealing dealers dealings dealing dealt deals delivers deliver delivery delivering deliveries delivered delivers delivering deliveries deliverable delivery delivery deliverable deliver delivers delivering deliver delivering deliveries delivery delivered deliveries deliverable delivery delivered deliveries delivers delivering deliveries transport transporting transportation transported transport transports transportation transport transportation transported transports transporting transports transported transport transporting transport transportation transports transporting transported transports transporter transporter transporters transporting transporter transports transportation transporting transporter transported transporting transporter transports transport transferring transferred transfers transferring transference transmitted transmits transmittable transmitter transmitters transmitted transmitting transmission transmissions transmitted transmissions transmitted transmitters transmitting transmissions transpired spiraled transpired transpired spiraled spiraled transpired transpires transpiring transparencies transparent transparency transparently transparency transparent transmits transmits transmitters transmitting transmission transmissions transmits transmits transmitter transmitting transmission transmission transmissions transmitted transmitters transmitting transmissions translated translations translator translating translates translator translating translates translations translator translating translates transliterated transliteration transliterates transliteration translating translates translator translating translatable translations translated translate translates translation translations translation translate translates translating translator translator translator’s translation translates translation translate transfers transferred transfers transferring transferable transfer transfers transfers transferred transferring transferable transfers transfers transferred transferring transfer transports transported transport transporting transportation transporters transporting transporter transported transportation transport transportation transporting transporters transported transports transfer transitions transitional transitioned transitions transition transition transitions transitioning transitioned transitions transition transition transitions transit transitionary transitions traverse traversed traverses traversing travelers travels traveled traveling travel traveler travelers travels traveled traveling traveler traveling travel journey journeys journey journeys journeys journey journeys traveled travels travelers journey journey journey journeys journeys journey travels traveled traveling travel journey journeys journey journeys journeys journey journeys traveled travels travelers journey journey journey journeys journeys traveled traveling traveling travels traveler journeys travels traveled journey journeys travelers travel traveling travels traveling traveled journey journey trips trips trips trips trips trip trips taken took taking taking take took takes taking taken took take takes taking taken trip trip trip trips trip trips traveling travels trip travels travels travels traveled trips taken took take takes takes takes taken take took took taking took took taken taken trip trips travel trips traveling traveling travels trip travel traveling trips trip trips traveling traveled trip trips taken traveled journeys trips journey journey travel travel travel traveler traveling travelled travelling traveller travelers travelled travelling traveller traveller travellers travelled travelling traveller travelling travelling travelled travelled travelling travelled travellers travellers travellers travelled travelling travelled travel visited visiting visitors visit visits visitor visited visiting visitors visits visits visit visiting visitor visits visits visit visiting visitor visitors visit visted visiting visited vistors visitor visitors visits visiting visited visted visiting visited vistors visitor visits visits visit visiting visitors visited vistors visits visitor visiting visit visits visitors visiting visited vistor visitors visit visits visiting visitor visits visited visted visits visiting visitors visitor visits visited vistor visitors visit vistors visitor visiting visiting viewers viewing viewers viewing viewing viewer views viewers viewing views view viewing view viewer viewership views viewer viewers viewing viewers viewed watching watch watched watching watches watch watch watches watched watching watch watch watches watched watching watches watching watches viewed viewing viewer viewing viewers viewership views viewers viewing views viewership viewed viewing viewer views viewer watchers watch watched watches watching watching watch watched watches watched watching watching watches watching watched watching watches observing observed observer observes observations observed observation observing observation observers observing observing observers observed observing observed observing observed observers observing observing observations observers observes observes observant observational observations observations observation observing observes observed observer observation observing observes observers observation observation observing observes observed observance observed observer observance observations observation observance observer observes observed observance observance observe observably observer observational observations observations observe observed observes observation observed observe observer observe observers observational observational observational observations observances observable observable obedience obedience obedient obey obediently obedience obediently obedient obeys obeys obey obedience obey obey obedience obey obey obedience obey obedience obeys obeys obedience obey obedience obey obelisk obelisk oblong oblong oblongness obsolete obsolescent obsolete obsolescence obsolesces obsolescing obsolete obsolete obsolescence obliteration obliterates obliterated obliterating obliterate obliterated oblivious oblivious obliviousness obliviously oblivious obliviously oblivious oblivion obscurant obscurity obscured obscuring obscure obscurer obscure obscurer obscure obscurity obscurer obscured obscured obscure obsequious obsequious obsequiously obediently obedient obediently abide adherences adherence adhere adheres adhered adherence adherence adherent adherents adherent adherents adherents adherents adherents adherence adherences adherence adhere adhered adhesion adhesions adhesive adhesive adhesives adieu adultery affluent affluence affliction afflictions afflicting afflictive afflicted affiliated affiliation affiliated affiliative affiliation affiliated affiliative affiliate affiliate affiliated affixes affix affix affixed affixes affiliation affiliated affiliative affluent aggrandizement aggrandizing aggravate aggravates aggravating aggravated aggravating aggrandizing aggregate aggregates aggregating aggregation aggregative aggregator aggregators aggregation aggregator aggregative aggregate aggregates aggregating aggregation aggregate aggregated aggregated aggregator aggregators aggregation aggregation aggregation aggregative aggregator aggregate aggregate aggregated aggregated aggregator aggregation aggregative aggregates aggregation aggregate aggregated aggregated aggregation aggregator aggregative aggregate aggregates aggregation aggregate aggregates aggregates aggregation aggregates aggregation aggregated aggregated aggregator aggregation aggregative aggregate aggregates aggregates aggregation aggregated aggregated aggregation aggregator aggregate aggregates aggregated aggregative aggregated aggregators agregate agregates agregating agregador agregados agregadora agregativas agregada agregadables agregativos agregado agradecidos agradecido agradecidos agradecido agradecido agradecido agradecimientos agradecimientos agradecer agradecida agradecido agradecido agradecidos agravement agrarian agriculture agriculture agriculture agricultural agriculturalists agriculture agnostic agnostics agonized agonizing agonizes agonizing agonies agony agonizes agonized agonizing ago ago ago ages ago ages ages ago ages ago ages ago ages ago ah ah ah ah alas alarmed alarm alarms alarm alarmist alarms alarmed alarmist alarmingly alarmed alarmingly alarmed alert alert alert alert alert alert alerts alert alerts alert alerts allege alleged allegations allegiant alleged allegations allegiance allegiances allegiances allegiance allegiance ally allies all-all-all-all-all-all-all-all-all-all-all-all-all-all-all-all-almost almost almost almost almost almost almost always always almost already alright alright alright already alright already allright alright alright already alright already allright all right alright alright alright already ally allies allies alliance alliance alliance allies allies alliances all-and-around altogether altogether altogether alongside along along alongside along alongside alongside along alongether alongside along along alongside together together together together together together all-and-around allied ally allies alliances alliances aligned alignment aligned alignments alignment aligned allied alignments aligns alignment align aligning alignment allied allegiance allegiance allegiance allied alignment alignments alignments alignment aligned aligned alongside alongside alliance ally alliances allies allies alliance allies alliances all around around around around around around around around surround surrounding surroundings surroundings surrounding surrounding surrounded surrounded surround surrounds surrounding surround surroundings surrounded surrounds surrround surrouning surrounding surrounds surround surrounding surroundings surround surrounded surroundings surrounds surrouding surrounding surrounding surrounds surroundings surroundings surround surroundings surrounding surrounds surrouund surrouding surrounds roundaround roundabout roughly roughly approximately approximately approximate approximately approximately approx approx appr approximately approximately roughly roughly approximates approximate approximation approximately approximately approximately approximate approximate approximates approximated approximates approximation approximate approximation approximates approximated approximation approximate approximation approximations approximations approximated approximates approximation approximately approximate approximate approximates approximation approximations approximated approximations approximates approximated approximated approximations approvable approval approval approving approvable approved approving approval approve approving approved approve appropriate appropriately appropriate appropriately appropriateness appropriately appropriate appropriateness appropriately approving appropriate appropriate appropriateness appropriate appropriate appropriately appropriate approving appropriateness appropriately appropriateness appropriate appropriately approved approval approvably approach approaches approached approaching approaching approaches approach approached approaching approaches appraise appraised appraising appraisal appraisal appraisals appreciable appreciation appreciated appreciative appreciation appreciate appreciates appreciative appreciation appreciating appreciably appreciates appreciably appreciation appreciated appreciate appreciatively appreciation appreciate appreciably appreciated appreciation appreciably appreciate appreciate appreciably appreciated appreciable appreciate appraisal apprehension apprehend apprehended apprehensive apprehends apprehending apprehensions apprehensive apprehension apprehend apprehends apprehending apprehensions appalled appallingly appalling appraisal appliances appliance appliances applied applied applying applications apply applying applies applicable applicability applicable application applicable applications applicable applicable applicants apply applies applying applied apprentice apprentices apprenticing apprenticeship apprentice apprenticed apprenticing apprenticeship apprentice apricot apricot apricots apricots apron aprons apt apt aptitude aptitude aptitudes apt aptitudes aptitude apter aptitude aptitudes aptitude aptitude apter aptitudes aptitude aptitude apter aptitudes aptitude appraised apprising appreciation appreciated appreciated appreciably appreciable appreciated appreciate appreciated appreciation appreciation appreciate appreciation appreciate appraisal appraisal appraising appraisals appreciated appreciation appreciate appreciable appreciate appreciated appraisal appraisal applause applaud applaud applause applaud applaud applause applaud applause applaud apprised apreciate apreciate apreciable apreciacion apreciamos apreciamos apreciamos apreciamos apreciando apreciaron apron apron apropos apropos apropos apropos apropos apropos april april april april april april as as as as as as as as as as as as as ass ass ass ass ass ass-ass-ass-ass-ass-ass-ass-ass-associated associated associate associates association associat associations associates associat associatives associative associated associations associates associative association associated associati associated association associational associates associated assorted assortment assortments assort assort sorts assort assort sorts assorted assortments sorted sorting sorts sorts sort sorted sort sorted sorting sorted sorts sort sorting sorts sort sorting sorts sorting sorts sort sorted sorting sorted sorts sorts sorting sorting sort assorted assortment assortment assorting assorted assortments sorted sorting sorts sort assortment assortment sort sorted sorting sorts sorted assortments sorted sorting sort assortments assortment sort sorted sorting sort sort of of of of of of of off off off off of off off off of of off off off off offset offsets offsetting offset offset offset offsetting offsets offsets offsets offsetting offsetting offsets offset off offsets offsets offsets offsets offsets offsets offsetting offset offsets offsetoffs offsets offset offsets offsetting offsets offsets offsetoffsets offsets offsetoffsetoffsetoffsetoffsetoffsetoffsetoffspring offspring offspring offspring offspring offspring offspring offspring offspring offspring offspring ofspring offspring ofspring offspring offspring offspring offspring origins originate originating origin originating origin origins originate originated originating original original original originality originally original original original original origination origins originate originate originated origin originates originating origins original original origination origination origin originate originating origin originate originated originate origins originate originating origin origins originated originating origination origination org org org org org org org org org org org org organ organ organs organism organisms organisms organizational organized organically organized organizations organizatio organizing organizational organizational organization organize organizing organize organized organize organizational organizations organization organization organizations organize organizing organizing organization organizational organ organ organ organs organism organisms organs organs organic organs organic orgasms orgasm orgasm organically orgasmic organize organized organizing organizations organizat organizational organizational organization organizations organizatio organize organizing organize organized organize organizational organization organizational organizati organizing organization organization organization organization organisms organisms organisms organism organisms organism organism organ organ organs organs organic organic organic organically organic organic organic organs organic organisms organ orchard orchards orchid orchids orchid orchids orchestr orchestrate orchestrated orchestrating orchestra orchestra orchestras orchestral orchestra orchestra orchalestre orchestral orchestra orchestra orchestra orchestral orchestras orchestrate orchestrated orchestr orchestrating orchid orchard orchar orchard orchid orchards orchar orchar orchar orchard orchards ore o

## 日誌記錄的結構化:結合 Structlog 的高效方式

日誌記錄是開發與維護應用程式時不可或缺的工具它不僅幫助我們追蹤程式的執行狀況還能在問題發生時提供寶貴的線索Python 的內建日誌模組雖然功能強大但有時會讓人感到繁瑣這時候Structlog 這樣的第三方日誌記錄函式庫就顯得尤為重要玄貓將帶領大家深入瞭解 Structlog 的使用方法並展示如何透過它來進行更高效的日誌記錄

### 基本使用與日誌格式

在開始之前讓我們先來看看 Structlog 的基本使用方式以下是一個簡單的範例展示如何組態 Structlog 來記錄日誌

```python
import structlog
import logging

structlog.configure(
    processors=[
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.add_log_level,
        structlog.dev.ConsoleRenderer()
    ],
    wrapper_class=structlog.make_filtering_bound_logger(logging.INFO)
)
logger = structlog.get_logger()

logger.info("This is an info message")

內容解密:

  • import structlog:匯入 Structlog 模組。
  • import logging:匯入 Python 的內建日誌模組。
  • structlog.configure:組態 Structlog 的處理器和包裝器類別。
    • structlog.processors.TimeStamper(fmt="iso"):將時間戳格式設為 ISO 8601 格式。
    • structlog.processors.add_log_level:新增日誌級別(例如 info、error)。
    • structlog.dev.ConsoleRenderer():使用控制檯渲染器來顯示日誌。
    • wrapper_class=structlog.make_filtering_bound_logger(logging.INFO):建立一個包裝器類別,過濾掉低於 INFO 級別的日誌。
  • logger = structlog.get_logger():取得一個結構化的日誌記錄器例項。
  • logger.info("This is an info message"):記錄一條 INFO 級別的訊息。

執行這段程式碼後,你會看到以下輸出(顯示時間戳已經被重新設定):

{
    "event": "This is an info message",
    "timestamp": "2024-04-04T16:01:35.636957Z",
    "level": "info"
}

捕捉異常並記錄

Structlog 不僅可以記錄普通訊息,還能捕捉和記錄異常。以下是一個範例,展示如何使用 Structlog 捕捉並記錄異常:

import logging
import structlog

structlog.configure(
    processors=[
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.add_log_level,
        structlog.dev.ConsoleRenderer()
    ],
    wrapper_class=structlog.make_filtering_bound_logger(logging.INFO)
)
logger = structlog.get_logger()

logger.info("A message before the exception")

try:
    10 / 0
except ZeroDivisionError:
    logger.exception("You cannot divide by zero!")

內容解密:

  • logger.info("A message before the exception"):在可能引發異常的操作之前記錄一條訊息。
  • try ... except ZeroDivisionError:捕捉除數為零的異常。
  • logger.exception("You cannot divide by zero!"):使用 exception 方法捕捉並記錄異常。

如果你在終端機中執行這段程式碼,你將會看到帶有彩色增強輸出的詳細異常資訊。這樣的輸出對於除錯非常有幫助。

如果你不需要顯示追蹤回溯資訊,可以使用 JSON 渲染器來生成更簡潔的輸出:

import logging
import structlog

structlog.configure(
    processors=[
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.add_log_level,
        structlog.processors.JSONRenderer()
    ],
    wrapper_class=structlog.make_filtering_bound_logger(logging.INFO)
)
logger = structlog.get_logger()

logger.info("A message before the exception")

try:
    10 / 0
except ZeroDivisionError:
    logger.exception("You cannot divide by zero!")

內容解密:

  • structlog.processors.JSONRenderer():使用 JSON 渲染器來生成 JSON 格式的日誌輸出。

執行這段程式碼後,你會得到以下 JSON 輸出:

{
    "event": "A message before the exception",
    "timestamp": "2024-04-04T17:44:20.779068Z",
    "level": "info"
}
{
    "exc_info": true,
    "event": "You cannot divide by zero!",
    "timestamp": "2024-04-04T17:44:20.779068Z",
    "level": "error"
}

日誌寫入磁碟

在實際應用中,我們經常需要將日誌寫入磁碟以便進行長期儲存和分析。Structlog 提供了 WriteLoggerFactory 來實作這一功能。以下是一個範例,展示如何將日誌寫入磁碟:

import logging
import structlog
from pathlib import Path

structlog.configure(
    processors=[
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.add_log_level,
        structlog.processors.JSONRenderer()
    ],
    wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
    logger_factory=structlog.WriteLoggerFactory(
        file=Path("app").with_suffix(".json").open("wt")
    )
)
logger = structlog.get_logger()

logger.info("This is an info message")

內容解密:

  • from pathlib import Path:匯入 Path 模組,用於處理檔案路徑。
  • Path("app").with_suffix(".json").open("wt"):建立一個名為 app.json 的檔案並開啟它以進行寫入操作。
  • logger_factory=structlog.WriteLoggerFactory(file=...):組態 Structlog 將日誌寫入指定的檔案。

執行這段程式碼後,你將會發現日誌已經被寫入到 app.json 檔案中。這樣的做法對於需要長期儲存和分析日誌的場景非常有幫助。

未來趨勢與實務應用評估

隨著技術的不斷進步,Structlog 的應用場景也在不斷擴充套件。未來,我們可以期待更多結合機器學習和大資料分析的日誌記錄技術出現,從而提供更高效的故障排除和效能最佳化工具。此外,隨著雲端運算的普及,將日誌上傳到雲端進行集中管理和分析也將成為一個重要趨勢。

無論是開發新應用還是維護現有系統,結構化的日誌記錄都能帶來顯著的好處。玄貓希望透過本章內容讓大家更好地理解和應用 Structolog 在 Python 中進行高效且結構化的日誌管理。希望大家能夠從中受益,並在實際工作中靈活運用這些技術。