SlideShare une entreprise Scribd logo
1  sur  34
Monitoring & Debugging
  Live Applications


Rob Coup
robert@coup.net.nz
Who am I?

• Koordinates
• Open data
  open.org.nz

• Geek
• Pythonista
Crash!


• trace ➭ reproduce ➭ simplify ➭ solve
• post-mortems suck
log everything
print "name=", name
print >>sys.stderr, "name=", name
#   http://www.flickr.com/photos/larimdame/2575986601
log.debug("name=%s", name)
Separation

• where the log messages are generated
• where the log output goes to
• runtime configuration
http://www.flickr.com/photos/theeerin/1108095143
“too Java”



     http://www.flickr.com/photos/lumaxart/2136948489
Too hard?
import logging
logging.basicConfig(level=logging.DEBUG,
                    file="/tmp/my.log")
log = logging.getLogger("somewhere")
Logger

• named (foo.bar.baz)
• debug() info() warn() error()
  critical() exception()
• % formatting
Handler

• does something with log messages
• stderr, files, syslog, HTTP, email, …
• filtering on logger hierarchy & level
Formatter


• formats the log output for a Handler
• time, file/line/function, thread, process, …
Logging Example
• log everything to /tmp/machine.log
• log startup and shutdown events to syslog
• quieten some noisy libraries (log warnings
  & errors only)
• email errors in machine.core to
  admin@example.com
In the code
logging.config.fileConfig("machine-logging.ini")



L = logging.getLogger("machine.startstop.start")
L.info("Starting the machine...")



L = logging.getLogger("machine.core.reactor")
L.error("Meltdown in Sector 7-G!")
Logging Example
# our normal formatter
[formatter_normal]
format=%(asctime)s machine[%(process)d]: %(name)s %(module)s
(%(lineno)d): %(message)s

# root logger, send everything to the file log
[logger_root]
level=NOTSET
handlers=file

# log to a file
[handler_file]
class=FileHandler
formatter=normal
args=('/tmp/machine.log','a')
Logging Example
# send startup/shutdown notices to syslog
[logger_startstop]
qualname=machine.startstop
handlers=syslog

# log to syslog
[handler_syslog]
class=handlers.SysLogHandler
formatter=normal
args=('/dev/log',)
Logging Example
# ignore messages below WARN for noisy libraries
[logger_noisylibs]
level=WARN
qualname=noisy,chatty,loud
propagate=0
handlers=
Logging Example
# send machine.core errors to the email handler
[logger_core]
qualname=machine.core
level=ERROR
handlers=email

# log to email
[handler_email]
class=handlers.SMTPHandler
formatter=email
args=('localhost', 'logs@a.com', ['admin@a.com'], 'LOG NOTICE')
Other Log Tools

• syslog-ng - centralise
• ack - grep on steroids
• less - a real pager
• Splunk - match & search & filter in bulk
Debuggers

• pdb works quite well
• even nicer with IPython
• pydbgr (Pydb) & WinPDB
Attach to running
         process
• I want “pdb -p 12345” (like gdb)
• Alternative:
  import pdb, signal
  signal.signal(signal.SIGUSR1, lambda x,y: pdb.set_trace())

• Then:
  kill -s SIGUSR1 <pid>
Remote Consoles




           http://www.flickr.com/photos/pasukaru76/3959355664/
Twisted Manhole

• Telnet/SSH server
• Access to interpreter namespace
• Interact with variables, call methods, …
Pretty easy
from twisted.conch import manhole_tap

manhole = manhole_tap.makeService({
    'namespace': namespace,
    # listen for Telnet connections on localhost:4777
    'telnetPort' : 'tcp:4777:interface=127.0.0.1',
    'sshPort' : None,
    # path to passwd-style file (username:password, plaintext)
    'passwd' : 'passwd',
})
manhole.setServiceParent(application)
But, uh, Twisted?!

• run the Twisted manhole in a thread
• leave normal Python code alone
• still get remote console
• need to handle concurrency!
Bots




       http://saiogaman.deviantart.com/art/Danbo-Wallpaper-107237965
Why?

• interact with our apps from our desktop
• have our apps interact with us
• great for non-technical users
Twisted Words


• for accessing IM services - XMPP, IRC, …
• Wokkel makes XMPP even easier
Abuse Bot
class TalkProtocol(xmppim.MessageProtocol):
    def onMessage(self, message):
        # we've received a message!
        reply = "nah, you're a " + str(message.body)

        response = domish.Element((None, "message"))
        response["to"] = message['from']
        response.addElement((None, 'body'), content=reply)
        self.send(response)
Outcomes

• Use logging
• Talk to your apps (console, bots)
• Have your apps talk to you (bots)
• You don’t need to have a Twisted app
Monitoring & Debugging
  Live Applications


Rob Coup
robert@coup.net.nz

Contenu connexe

Tendances

Rapid Application Design in Financial Services
Rapid Application Design in Financial ServicesRapid Application Design in Financial Services
Rapid Application Design in Financial ServicesAerospike
 
Monitoring with Syslog and EventMachine (RailswayConf 2012)
Monitoring  with  Syslog and EventMachine (RailswayConf 2012)Monitoring  with  Syslog and EventMachine (RailswayConf 2012)
Monitoring with Syslog and EventMachine (RailswayConf 2012)Wooga
 
Time tested php with libtimemachine
Time tested php with libtimemachineTime tested php with libtimemachine
Time tested php with libtimemachineNick Galbreath
 
Fluentd - CNCF Paris
Fluentd - CNCF ParisFluentd - CNCF Paris
Fluentd - CNCF ParisHorgix
 
Ansible tips & tricks
Ansible tips & tricksAnsible tips & tricks
Ansible tips & tricksbcoca
 
Ansible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife OrchestrationAnsible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife Orchestrationbcoca
 
More than syntax
More than syntaxMore than syntax
More than syntaxWooga
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.jsPrabin Silwal
 
From nothing to Prometheus : one year after
From nothing to Prometheus : one year afterFrom nothing to Prometheus : one year after
From nothing to Prometheus : one year afterAntoine Leroyer
 
Rapid dev env DevOps Warsaw July 2014
Rapid dev env DevOps Warsaw July 2014Rapid dev env DevOps Warsaw July 2014
Rapid dev env DevOps Warsaw July 2014blndrt
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.jsPiotr Pelczar
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsSyncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsPôle Systematic Paris-Region
 
Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in PythonMosky Liu
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsGraham Dumpleton
 
OSDC 2013 | Ansible: configuration management doesn't have to be complicated ...
OSDC 2013 | Ansible: configuration management doesn't have to be complicated ...OSDC 2013 | Ansible: configuration management doesn't have to be complicated ...
OSDC 2013 | Ansible: configuration management doesn't have to be complicated ...NETWAYS
 

Tendances (20)

Rapid Application Design in Financial Services
Rapid Application Design in Financial ServicesRapid Application Design in Financial Services
Rapid Application Design in Financial Services
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Monitoring with Syslog and EventMachine (RailswayConf 2012)
Monitoring  with  Syslog and EventMachine (RailswayConf 2012)Monitoring  with  Syslog and EventMachine (RailswayConf 2012)
Monitoring with Syslog and EventMachine (RailswayConf 2012)
 
Time tested php with libtimemachine
Time tested php with libtimemachineTime tested php with libtimemachine
Time tested php with libtimemachine
 
Fluentd - CNCF Paris
Fluentd - CNCF ParisFluentd - CNCF Paris
Fluentd - CNCF Paris
 
Ansible tips & tricks
Ansible tips & tricksAnsible tips & tricks
Ansible tips & tricks
 
Ansible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife OrchestrationAnsible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife Orchestration
 
More than syntax
More than syntaxMore than syntax
More than syntax
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.js
 
From nothing to Prometheus : one year after
From nothing to Prometheus : one year afterFrom nothing to Prometheus : one year after
From nothing to Prometheus : one year after
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
Erlang and Elixir
Erlang and ElixirErlang and Elixir
Erlang and Elixir
 
Node.js
Node.jsNode.js
Node.js
 
Rapid dev env DevOps Warsaw July 2014
Rapid dev env DevOps Warsaw July 2014Rapid dev env DevOps Warsaw July 2014
Rapid dev env DevOps Warsaw July 2014
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsSyncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
 
Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in Python
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
 
OSDC 2013 | Ansible: configuration management doesn't have to be complicated ...
OSDC 2013 | Ansible: configuration management doesn't have to be complicated ...OSDC 2013 | Ansible: configuration management doesn't have to be complicated ...
OSDC 2013 | Ansible: configuration management doesn't have to be complicated ...
 

Similaire à Monitoring and Debugging your Live Applications

Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Itzik Kotler
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementLaurent Leturgez
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on PythonSumit Raj
 
System insight without Interference
System insight without InterferenceSystem insight without Interference
System insight without InterferenceTony Tam
 
Go Web Development
Go Web DevelopmentGo Web Development
Go Web DevelopmentCheng-Yi Yu
 
#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and Protocols#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and ProtocolsPhilippe Back
 
Ultimate Unix Meetup Presentation
Ultimate Unix Meetup PresentationUltimate Unix Meetup Presentation
Ultimate Unix Meetup PresentationJacobMenke1
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak PROIDEA
 
MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsPetr Dvorak
 
Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.CocoaHeads France
 
theday, windows hacking with commandline
theday, windows hacking with commandlinetheday, windows hacking with commandline
theday, windows hacking with commandlineidsecconf
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscriptBill Buchan
 
InSecure Remote Operations - NullCon 2023 by Yossi Sassi
InSecure Remote Operations - NullCon 2023 by Yossi SassiInSecure Remote Operations - NullCon 2023 by Yossi Sassi
InSecure Remote Operations - NullCon 2023 by Yossi SassiYossi Sassi
 
Lotuscript for large systems
Lotuscript for large systemsLotuscript for large systems
Lotuscript for large systemsBill Buchan
 
Sticky Keys to the Kingdom
Sticky Keys to the KingdomSticky Keys to the Kingdom
Sticky Keys to the KingdomDennis Maldonado
 
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class Chris Gates
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Godreamwidth
 
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013midnite_runr
 

Similaire à Monitoring and Debugging your Live Applications (20)

Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)
 
Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data management
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
System insight without Interference
System insight without InterferenceSystem insight without Interference
System insight without Interference
 
Go Web Development
Go Web DevelopmentGo Web Development
Go Web Development
 
#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and Protocols#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and Protocols
 
Ultimate Unix Meetup Presentation
Ultimate Unix Meetup PresentationUltimate Unix Meetup Presentation
Ultimate Unix Meetup Presentation
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
 
MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS Topics
 
Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.
 
theday, windows hacking with commandline
theday, windows hacking with commandlinetheday, windows hacking with commandline
theday, windows hacking with commandline
 
Golang
GolangGolang
Golang
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
DIY Java Profiling
DIY Java ProfilingDIY Java Profiling
DIY Java Profiling
 
InSecure Remote Operations - NullCon 2023 by Yossi Sassi
InSecure Remote Operations - NullCon 2023 by Yossi SassiInSecure Remote Operations - NullCon 2023 by Yossi Sassi
InSecure Remote Operations - NullCon 2023 by Yossi Sassi
 
Lotuscript for large systems
Lotuscript for large systemsLotuscript for large systems
Lotuscript for large systems
 
Sticky Keys to the Kingdom
Sticky Keys to the KingdomSticky Keys to the Kingdom
Sticky Keys to the Kingdom
 
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
The Dirty Little Secrets They Didn’t Teach You In Pentesting Class
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Go
 
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
 

Plus de Robert Coup

Curtailing Crustaceans with Geeky Enthusiasm
Curtailing Crustaceans with Geeky EnthusiasmCurtailing Crustaceans with Geeky Enthusiasm
Curtailing Crustaceans with Geeky EnthusiasmRobert Coup
 
/me wants it. Scraping sites to get data.
/me wants it. Scraping sites to get data./me wants it. Scraping sites to get data.
/me wants it. Scraping sites to get data.Robert Coup
 
Map Analytics - Ignite Spatial
Map Analytics - Ignite SpatialMap Analytics - Ignite Spatial
Map Analytics - Ignite SpatialRobert Coup
 
Twisted: a quick introduction
Twisted: a quick introductionTwisted: a quick introduction
Twisted: a quick introductionRobert Coup
 
Distributed-ness: Distributed computing & the clouds
Distributed-ness: Distributed computing & the cloudsDistributed-ness: Distributed computing & the clouds
Distributed-ness: Distributed computing & the cloudsRobert Coup
 
Geo-Processing in the Clouds
Geo-Processing in the CloudsGeo-Processing in the Clouds
Geo-Processing in the CloudsRobert Coup
 
Maps are Fun - Why not on the web?
Maps are Fun - Why not on the web?Maps are Fun - Why not on the web?
Maps are Fun - Why not on the web?Robert Coup
 
Fame and Fortune from Open Source
Fame and Fortune from Open SourceFame and Fortune from Open Source
Fame and Fortune from Open SourceRobert Coup
 

Plus de Robert Coup (9)

Curtailing Crustaceans with Geeky Enthusiasm
Curtailing Crustaceans with Geeky EnthusiasmCurtailing Crustaceans with Geeky Enthusiasm
Curtailing Crustaceans with Geeky Enthusiasm
 
/me wants it. Scraping sites to get data.
/me wants it. Scraping sites to get data./me wants it. Scraping sites to get data.
/me wants it. Scraping sites to get data.
 
Map Analytics - Ignite Spatial
Map Analytics - Ignite SpatialMap Analytics - Ignite Spatial
Map Analytics - Ignite Spatial
 
Twisted: a quick introduction
Twisted: a quick introductionTwisted: a quick introduction
Twisted: a quick introduction
 
Django 101
Django 101Django 101
Django 101
 
Distributed-ness: Distributed computing & the clouds
Distributed-ness: Distributed computing & the cloudsDistributed-ness: Distributed computing & the clouds
Distributed-ness: Distributed computing & the clouds
 
Geo-Processing in the Clouds
Geo-Processing in the CloudsGeo-Processing in the Clouds
Geo-Processing in the Clouds
 
Maps are Fun - Why not on the web?
Maps are Fun - Why not on the web?Maps are Fun - Why not on the web?
Maps are Fun - Why not on the web?
 
Fame and Fortune from Open Source
Fame and Fortune from Open SourceFame and Fortune from Open Source
Fame and Fortune from Open Source
 

Dernier

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Dernier (20)

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

Monitoring and Debugging your Live Applications

  • 1. Monitoring & Debugging Live Applications Rob Coup robert@coup.net.nz
  • 2. Who am I? • Koordinates • Open data open.org.nz • Geek • Pythonista
  • 3. Crash! • trace ➭ reproduce ➭ simplify ➭ solve • post-mortems suck
  • 7. # http://www.flickr.com/photos/larimdame/2575986601
  • 9. Separation • where the log messages are generated • where the log output goes to • runtime configuration
  • 11. “too Java” http://www.flickr.com/photos/lumaxart/2136948489
  • 12. Too hard? import logging logging.basicConfig(level=logging.DEBUG, file="/tmp/my.log") log = logging.getLogger("somewhere")
  • 13. Logger • named (foo.bar.baz) • debug() info() warn() error() critical() exception() • % formatting
  • 14. Handler • does something with log messages • stderr, files, syslog, HTTP, email, … • filtering on logger hierarchy & level
  • 15. Formatter • formats the log output for a Handler • time, file/line/function, thread, process, …
  • 16. Logging Example • log everything to /tmp/machine.log • log startup and shutdown events to syslog • quieten some noisy libraries (log warnings & errors only) • email errors in machine.core to admin@example.com
  • 17. In the code logging.config.fileConfig("machine-logging.ini") L = logging.getLogger("machine.startstop.start") L.info("Starting the machine...") L = logging.getLogger("machine.core.reactor") L.error("Meltdown in Sector 7-G!")
  • 18. Logging Example # our normal formatter [formatter_normal] format=%(asctime)s machine[%(process)d]: %(name)s %(module)s (%(lineno)d): %(message)s # root logger, send everything to the file log [logger_root] level=NOTSET handlers=file # log to a file [handler_file] class=FileHandler formatter=normal args=('/tmp/machine.log','a')
  • 19. Logging Example # send startup/shutdown notices to syslog [logger_startstop] qualname=machine.startstop handlers=syslog # log to syslog [handler_syslog] class=handlers.SysLogHandler formatter=normal args=('/dev/log',)
  • 20. Logging Example # ignore messages below WARN for noisy libraries [logger_noisylibs] level=WARN qualname=noisy,chatty,loud propagate=0 handlers=
  • 21. Logging Example # send machine.core errors to the email handler [logger_core] qualname=machine.core level=ERROR handlers=email # log to email [handler_email] class=handlers.SMTPHandler formatter=email args=('localhost', 'logs@a.com', ['admin@a.com'], 'LOG NOTICE')
  • 22. Other Log Tools • syslog-ng - centralise • ack - grep on steroids • less - a real pager • Splunk - match & search & filter in bulk
  • 23. Debuggers • pdb works quite well • even nicer with IPython • pydbgr (Pydb) & WinPDB
  • 24. Attach to running process • I want “pdb -p 12345” (like gdb) • Alternative: import pdb, signal signal.signal(signal.SIGUSR1, lambda x,y: pdb.set_trace()) • Then: kill -s SIGUSR1 <pid>
  • 25. Remote Consoles http://www.flickr.com/photos/pasukaru76/3959355664/
  • 26. Twisted Manhole • Telnet/SSH server • Access to interpreter namespace • Interact with variables, call methods, …
  • 27. Pretty easy from twisted.conch import manhole_tap manhole = manhole_tap.makeService({ 'namespace': namespace, # listen for Telnet connections on localhost:4777 'telnetPort' : 'tcp:4777:interface=127.0.0.1', 'sshPort' : None, # path to passwd-style file (username:password, plaintext) 'passwd' : 'passwd', }) manhole.setServiceParent(application)
  • 28. But, uh, Twisted?! • run the Twisted manhole in a thread • leave normal Python code alone • still get remote console • need to handle concurrency!
  • 29. Bots http://saiogaman.deviantart.com/art/Danbo-Wallpaper-107237965
  • 30. Why? • interact with our apps from our desktop • have our apps interact with us • great for non-technical users
  • 31. Twisted Words • for accessing IM services - XMPP, IRC, … • Wokkel makes XMPP even easier
  • 32. Abuse Bot class TalkProtocol(xmppim.MessageProtocol): def onMessage(self, message): # we've received a message! reply = "nah, you're a " + str(message.body) response = domish.Element((None, "message")) response["to"] = message['from'] response.addElement((None, 'body'), content=reply) self.send(response)
  • 33. Outcomes • Use logging • Talk to your apps (console, bots) • Have your apps talk to you (bots) • You don’t need to have a Twisted app
  • 34. Monitoring & Debugging Live Applications Rob Coup robert@coup.net.nz

Notes de l'éditeur

  1. When we encounter a problem with our live applications (on the web or elsewhere), we often have no opportunity to follow the normal debugging process through to its conclusion. The app needs to get back up, stat! And trying to piece together logs afterwards is hard.
  2. I believe in logging virtually everything - if it helps during development it&amp;#x2019;ll probably help during debugging. Certainly beats &amp;#x201C;turning up&amp;#x201D; or adding logging, restarting the app, and waiting for the problem to happen again.
  3. who logs like this?
  4. What about this? Standard error is good, right? Separates our logging from any real output...
  5. the problem with these is you end up commenting everything just to make it shut the hell up. And then have to uncomment to start talking again. http://www.flickr.com/photos/larimdame/2575986601
  6. whoa? an actual logging framework? Yes, Python has a powerful builtin logging framework with the logging module, we should use it.
  7. Logging separates the source of the messages from the output. So you can turn up and down the level in configuration (live even), or point logs somewhere else, without ever going back into the code itself.
  8. Python&amp;#x2019;s logging module gets a real bad rap about the place... http://www.flickr.com/photos/theeerin/1108095143
  9. Lots of people think it&amp;#x2019;s based too closely on log4j. How many ways are there to specify log.debug? It&amp;#x2019;s actually a pretty clean design that works fast. http://www.flickr.com/photos/lumaxart/2136948489
  10. Others say its too hard. Seriously, 3x lines of code to get file logging going for an entire app is not &amp;#x201C;too hard&amp;#x201D;
  11. The first key component of logging is a Logger, which generates log messages. Loggers are named by the developer, usually based on where the code is. The names form a hierarchy using the dots. Then we have the debugging methods at different levels. For the exception() one it&amp;#x2019;ll just pick up on the current exception and log a traceback all by itself. And all the logging methods accept % formatting via their arguments, so we don&amp;#x2019;t have to build strings just to chuck them away.
  12. Handlers do something with log messages. They might write it to the console, to a file, send to a web server, post an email, stick it in Syslog or the NT event log, or a multitude of other things. They can filter out which messages they apply to, so we can log everything to a file as well as email just the critical errors.
  13. The last one is a formatter. What are our log messages going to look like? The formatter has access to the code location where the log message came from, as well as the process, thread, the time, and so on.
  14. So lets start with an example. We have our &amp;#x201C;machine&amp;#x201D; application, which wants to log different things to various places.
  15. So in our code, we don&amp;#x2019;t need much. Somewhere we call fileConfig to set things up, pointing to our ini-style config. After that we just get logger objects by name, then call methods on them.
  16. so, we want to send everything to a file by default. This bit of config will do that. We set up a format for our log lines. Since the loggers form a hierarchy, the root one is at the top and everything floats up there eventually. And we tell it to use a FileHandler pointing to our log.
  17. Next, startup/shutdown messages to syslog. Anything logged by a logger named machine.startstop.something will end up here. We use a SysLogHandler to get it into syslog for us.
  18. We want to squash the debug &amp; info messages for three libraries: noisy, chatty, loud. We do this by setting propagate=0, which prevents the messages from bubbling up to the root logger. And we have no handler, so they don&amp;#x2019;t go anywhere else.
  19. Then we want to send core errors (machine.core.anything) by email. We use level=error to filter out just the errors. And then we use a SMTPHandler to log via email.
  20. And that&amp;#x2019;s prettymuch logging. There are some other tools I&amp;#x2019;m fond of, since you&amp;#x2019;re logging everything... Syslog-ng can help pull logs from multiple machines into one place. ack &amp; less are the awesome duo of finding anything in text. And Splunk is a great tool for matching and tracing lots of events across multiple servers.
  21. (DEMO 4-1.py)
  22. The next thing in our debugging arsenal is a remote console. Don&amp;#x2019;t you wish you could just look inside your app and find out what it&amp;#x2019;s thinking, rather than hypothesising? Remote consoles certainly beats trial and error, or reconstructing chains of events from log files. We have the technology to just ask it :) http://www.flickr.com/photos/pasukaru76/3959355664/
  23. Who&amp;#x2019;s heard of Twisted? The twisted library does lots of magic things, but one of the cool ones is a telnet or ssh server that gives access into a running python environment. You can read and change variables, call methods, whatever you want. (DEMO 2-1.py)
  24. And the code is pretty simple. Basically we create a dictionary object we use as a namespace for where the user ends up. We specify an IP and a port (and encryption keys if you want an ssh shell), and a file with usernames and passwords. that&amp;#x2019;s it. At least, if you have a Twisted app.
  25. Twisted is an asynchronous framework, it&amp;#x2019;s single threaded with an event loop, and doesn&amp;#x2019;t work in the same way most Python code does. But we can run the Twisted part (which does our manhole) in a separate thread, leaving our normal code alone. The only downside? we have to handle concurrency if we&amp;#x2019;re changing things :) (DEMO 2-2.py)
  26. The 3rd idea i want to talk about is robots. We can review our app&amp;#x2019;s progress with logs. We can telnet right inside it for hardcore inspection. But we can also get it talking to us via instant messaging. http://saiogaman.deviantart.com/art/Danbo-Wallpaper-107237965
  27. everybody runs IM of some sort, its already open on the desktop, it just works. Our apps can say to us, in real time: &amp;#x201C;hey, Rob, I&amp;#x2019;m not happy&amp;#x201D;. Plus, the marketing guy down the hall might like to get pinged if someone orders 100 copies of our awesome software. Bots can do this.
  28. Among its arsenal of networking awesomeness, twisted also does XMPP (also known as Jabber). It&amp;#x2019;ll also do IRC and some other stuff, but we&amp;#x2019;ll focus on XMPP for now. Basically it&amp;#x2019;s an asynchronous protocol for passing bits of XML around. No polling required. There&amp;#x2019;s a library called Wokkel which makes XMPP even easier than Words does. (DEMO 3-1.py)
  29. This is the talk-ey part of the code for that example. It gets a message object in, then composes and sends a reply. Do whatever you want in these methods. And your app can call .send() itself anytime to send messages.
  30. And this is basically what I&amp;#x2019;d like you to take away. Arm yourself with some great tools and debugging and keeping an eye on your apps will be a lot easier. Trial and error sucks, move on!